看到报错信息 有Access to XMLHttpRequest by CORS policy: No 'Access-Control-Allow-Origin' 这些关键字 就代表是跨域错误 -->
产生跨域的原因
由浏览器的同源策略造成的
同域名,同端口,同协议(http 和 https)
跨域解决方案1
CORS跨域资源共享
服务端:header("Access-Control-Allow-Origin:*");
“*”表示所有的域都可以接受
跨域解决方案2
jsonp
复制代码
复制代码
动态创建script标签,使用jQuery的jsonp请求 优点 兼容性强&不受同源策略的限制 缺点 只能用get方法,不能使用post方法
<script src="./jquery-1.12.4.js"></script>
<script>
使用jsonp解决跨域
$.ajax({
url:"http://192.168.1.2/a.php",
type:"get",
定义发送jsonp请求
dataType:'jsonp',
更改定义的参数名
jsonp:'kyFn',//修改callback名称,但是php中也要修改成相对应的函数名
指定jsonp发送的回调函数名(可以任意起名字,无需对应)
jsonpCallback:'callBack',
success:function (res){
document.write(res);
}
});
function callBack(res){
document.write(res);
}
$.ajax({
url:"http://localhost:3000",
success:function(res){
console.log(res);
},
error:function(err){
console.log(err)
}
})