什么是跨域?
使用js获取数据时,涉及到的两个url只要协议、域名、端口有任何一个不同,都被当作是不同的域,相互访问就会有跨域问题。
例如客户端的域名是www.redis.com.cn,而请求的域名是www.264.cn
如果直接使用ajax访问,会有以下错误
XMLHttpRequest cannot load http://www.264.cn/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.redis.com.cn' is therefore not allowed access.
如何解决跨域?
在服务器页面的Response header中加入如下内容,可以实现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:* 表示允许任何域名跨域访问
如