Access-Control-Allow-Origin:ajax 跨域访问

来源:互联网 发布:sql server数据备份 编辑:程序博客网 时间:2024/05/16 13:02

在使用jquery的$.ajax跨域访问的时候,如客户端域名是www.test.com,而服务器端是www.test2.com,在客户端通过ajax访问服务器端的资源将会报跨域错误:

XMLHttpRequest cannot load http://www.test2.com/test.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.test.com' is therefore not allowed access.

ajax跨域访问的解决方法很多,很多人推荐JSONP方法,这种方法只支持GET方式,不如POST方式安全。有兴趣的可以自行搜索,这里讲另外一种方法。

这时候只要在被请求的响应头中加入下面语句:

// 指定允许其他域名访问  header('Access-Control-Allow-Origin:*');  // 响应类型  header('Access-Control-Allow-Methods:POST');  // 响应头设置  header('Access-Control-Allow-Headers:x-requested-with,content-type');  

就可以实现跨域请求了。

Access-Control-Allow-Origin:* 表示允许任何域名跨域访问

如果需要指定某域名才允许跨域访问,只需把Access-Control-Allow-Origin:*改为Access-Control-Allow-Origin:允许的域名

eg:header('Access-Control-Allow-Origin:http://www.test.com');



0 0