直接用ajax访问本地服务器上的php文件报错,请问一下怎么才能访问到本地服务器上的文件不报错?

$.ajax({

type:"get",
url:"http://192.168.0.111:80/Index/index.php",
async:true,
success:function(res){
    console.log(res)
},
error:function(err){
    console.log("error:"+JSON.stringify(err));
}

});

在服务器下的文件可以用ajax访问到php文件

报错代码
XMLHttpRequest cannot load http://192.168.0.111/Index/in... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access

用vue脚手架写的,不用也一样报类似的错误

阅读 4.3k
3 个回答

跨域了。AJAX同源策略不允许跨域访问。
解决方法有二:
切换到相同的域下,即页面和PHP文件均位于192.168.0.111下或localhost:8080下
或者在服务器返回时加入 Access-Control-Allow-Origin:* 头,即可解决。既然服务器搭建在本地,这一项应该不难实现。

网上也有说利用JSONP解决的,自己没试过,可能可行。

dataType: 'jsonp',
crossDomain: true,

简单说就是跨域了。

网页使用的localhost,远程请求是 192.168.. 都是使用的本地的 ip ,我想你应该用的虚拟机,而且还是单页应用。

所以你需要在那个服务器设置 Access-Control-Allow-Origin:* 就可以了。

另外你这个url http://192.168.0.111:80/Index/index.php 就没必要写 80 端口了吧,http 协议浏览器默认的就是使用 80 端口。

常识问题……

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题