(服务端处理)ajax 设置Access-Control-Allow-Origin实现跨域访问
原文:http://www.52php.cn/article/p-harvrahb-bkb.html ajax跨域访问是一个老问题了,解决方法很多,比较常用的是JSONP方法,JSONP方法是一种非官方方法,而且这种方法只支持GET方式,不如POST方式安全。 即使使用jquery的jsonp方法,type设为POST,也会自动变为GET。 官方问题说明: “script”: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter,“_=[TIMESTAMP]“,to the URL unless the cache option is set to true.Note: This will turn POSTs into GETs for remote-domain requests. 如果跨域使用POST方式,可以使用创建一个隐藏的iframe来实现,与ajax上传图片原理一样,但这样会比较麻烦。 因此,通过设置Access-Control-Allow-Origin来实现跨域访问比较简单。 例如:客户端的域名是www.client.com,而请求的域名是www.server.com 如果直接使用ajax访问,会有以下错误 XMLHttpRequest cannot load http://www.server.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.client.com' is therefore not allowed access. 在被请求的Response header中加入
就可以实现ajax POST跨域访问了。 代码如下: client.html路径:http://www.client.com/client.html
[html]
copy
server.php路径:http://www.server.com/server.php copy
Access-Control-Allow-Origin:*表示允许任何域名跨域访问 如果需要指定某域名才允许跨域访问,只需把Access-Control-Allow-Origin:*改为Access-Control-Allow-Origin:允许的域名 例如:header('Access-Control-Allow-Origin:http://www.client.com'); 设置多个域名允许访问,这里需要用php处理一下 例如允许 www.client.com 与 www.client2.com 可以跨域访问 server.php 修改为 copy
|
- ResultSet转换成XML字符串传递提取组成String[].
- 正则表达式 – r分隔符不在括号中
- logback logback.xml常用配置详解(三) <filter>
- "WEAK, STRONG, UNOWNED, 老天爷!" - Swift中的引用
- ruby – Jekyll是否允许仅使用帖子的标题作为URL?
- C++11 std::bind
- 从XML节点java生成/获取xpath
- Swift获取命名空间(namespace),动态加载类
- xmlns是什么——XML Namespace Explained
- 修复SQLite-database disk image is malformed