1、简单方式1(jq)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="js/jquery-3.2.1.js"></script>
<script>
$.ajax({
type:"get",
url:"http://127.0.0.1/weather3.php",
dataType:"jsonp"
}).then(data=>{
document.write(data);
})
</script>
</body>
</html>
<?php
@$fun=$_REQUEST["callback"];
$weather="天气晴 6~8 from 本地";
echo "$fun('$weather')";
?>
注:是用带参数请求url,script会先生成再删去
2、在服务器端加请求头<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="js/jquery-3.2.1.js"></script>
<script>
$.ajax({
type:"get",
url:"http://127.0.0.1/weather4.php",
}).then(data=>{
document.write(data);
})
</script>
</body>
</html><?php
header("Access-Control-Allow-Origin:*");
$weather="天气晴 6~8 from 本地";
echo $weather;
?>
本文介绍了两种实现跨域请求的方法:一是使用JSONP并通过jQuery发起GET请求;二是通过设置服务器响应头来允许跨域访问。这两种方法均实现了客户端与服务器间的跨域数据交换。
534

被折叠的 条评论
为什么被折叠?



