社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
问题描述:"XMLHttpRequest cannot load http://xxx.xxx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access."/xxx.html (0)
出现原因:ajax本身实际上是通过XMLHttpRequest对象来进行数据的交互,而浏览器处于安全考虑,不允许js代码进行跨域操作,所以会出现这个错误
解决方法:
方案一.一般jQuery解决跨域是通过jsonp的方式,添加callback=xxx,服务器返回xxx(...),这种方式需要服务器代码帮忙
举个栗子:在index.html中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var url = "jsonp.php?num1=1&num2=2&callbackname=jsonp_callback"; //访问localhost下的jsonp.php
var scriptTag = document.createElement("script"); //创建一个script标签
scriptTag.setAttribute("src",url); //设置script的src属性
document.body.appendChild(scriptTag); //将script标签添加到body中
});
//回调函数
var jsonp_callback = function(resultObj){
$("#res").text(resultObj);
}
</script>
</head>
<body>
<p id="res"></p>
</body>
</html>
jsonp.php
<?php
$num1= $_GET["num1"];
$num2= $_GET["num2"];
$result = $num1 + $num2;
$callbackname = $_GET["callbackname"]; //回调函数名称
echo "$callbackname($result)";
?>
最终index.html中显示 3
方案二.通过CORS(跨域资源共享) Proxy 对请求进行转发,就可以实现跨域访问。
如: 请求地址是 http://op.juhe.cn/onebox/weather/query?key=3611a1e75f91ff1544fc9f84ec489021&dtype=json&cityname=武汉
则修改为 跨域服务器地址/ http://op.juhe.cn/onebox/weather/query?key=3611a1e75f91ff1544fc9f84ec489021&dtype=json&cityname=武汉
(例如:http://proxy.e12e.com/? http://op.juhe.cn/onebox/weather/query?key=3611a1e75f91ff1544fc9f84ec489021&dtype=json&cityname=武汉)这样就可以很方便使用代理的方式来访问api接口了
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!