ajax如何跨域?

1、创建一个空的html文件test.html,引入jquery

2、调用ajax

$.ajax({
    url: 'http://XXXXXXXXXXXXXX',
    type: 'post',
    success: function() {
        console.log('成功');
    },
    error: function() {
        console.log('失败');
    }
});

3、url中给出的是项目的接口地址,直接访问是可以得到数据的

4、为何直接在浏览器打开test.html就会打印失败,并提示

XMLHttpRequest cannot load *******(接口地址). No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'file://' is therefore not allowed access.

5、这是跨域导致的错误吗?该如何解决?

补充:1、后端返回的数据格式是json
2、同事给的方案:在tomcat中配cors的filter,添加了相关jar包(cors-filter-2.5,java-property-utils-1.10),不起作用

阅读 3.8k
5 个回答

在windows系统中,新建chrome浏览器的快捷方式,右键-目标,加入 --disable-web-security --user-data-dir

在mac系统中,终端执行:open -a "Google Chrome" --args --disable-web-security --user-data-dir

跨域解决方法:
方法1:浏览器设置跨域
方法2:加代理
3:楼下补充

--
关于:Access-Control-Allow-Origin

a.com/index.html跨域调用b.com/apib.com/api需要在Response Header中设置Access-Control-Allow-Origin: a.com。意思是我b.com/api允许a.com下的网站跨域调用我的资源

网站如果可以使用JSONP的话,可以跳过跨域问题,如果不支持,就请你的后端帮你解决吧。。

服务器端设置response的head
前端ajax配置
xhrFields:{withCredentials: true},
crossDomain:true,
此方法是通过CROS解决

在请求的地址那边,代码头部添加: header('Access-Control-Allow-Origin: 允许的域名(协议 + 域名)')

js 请求,所属域名(协议 + 域名) https://www.request.com

$.ajax(
    url: https://www.getRequest.com/response.php ,
    type: 'post' , 
    success: function(){
        console.log('跨域请求成功!');
    } ,
    error: function(){
        console.log('跨域请求失败!');
    }
);

服务端,所属域名(协议 + 域名):https://www.getRequest.com

// response.php 文件

<?php
// 注意,这句代码一定要加在代码的顶部,其他的地方会跨域会失败
header('Access-Control_Allow-Origin: https://www.request.com');

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