跨域

JS请求后台数据报错:

XMLHttpRequest cannot load http://192.168.1.163/ajaxdemo/server.php?number=101. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.

这是跨域访问。

跨域实现的过程大致如下:

从 http://www.a.com/test.html 发起一个跨域请求,

请求的地址为: http://www.b.com/test.php

如果 服务器B返回一个如下的header

Access-Control-Allow-Origin: http://www.a.com

那么,这个来自 http://www.a.com/test.html 的跨域请求就会被通过。

 

如上所知,总结解决办法如下:

 

1、如果请求的url是aspx页面,则需要在aspx页面中添加代码:Response.AddHeader("Access-Control-Allow-Origin", "*");

 

2、如果请求的url是PHP页面,则需要在PHP页面中添加代码:header("Access-Control-Allow-Origin: *");

 

3、如果请求的url是静态的html页面,则需要在页面中添加meta标签代码:<meta http-equiv="Access-Control-Allow-Origin" content="*" />

 

如果服务器端可以确定是要被哪些域名访问,最好是能把以上代码中的“*”代替为具体的域名,这样做可以相应的增强安全性。

posted @ 2016-06-07 15:26  zhoudingzhao  阅读(166)  评论(0编辑  收藏  举报