jQuery XDomainRequest 是一个利用 XDomainRequest 对象为 IE8、IE9 实现跨域资源共享(CORS - Cross Origin Resource Sharing)的 jQuery 插件。
约束:
1. 使用 $.ajax 发送请求,jQuery 版本需在 1.5+
2. 服务端需设置 header:header('Access-Control-Allow-Origin:http://angular.js');
3. 请求方式仅限:GET / POST
4. 协议仅限:HTTP / HTTPS,且必须相同
5. 仅限异步请求
经验:
服务端设置 header('Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS'); 时,各浏览器跨域支持情况有差异。
代码:
api.php:
<?php
// 指定可信任的域名来接收响应信息
header('Access-Control-Allow-Origin:http://angular.js');
// 允许携带 用户认证凭据(也就是允许客户端发送的请求携带Cookie)
header('Access-Control-Allow-Credentials:true');
//header('Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS');
//header('Access-Control-Allow-Headers:Content-Type, Authorization, Content-Length, X-Requested-With, Accept, x-csrf-token, origin');
$type = $_SERVER['REQUEST_METHOD'];
parse_str(file_get_contents('php://input'), $data);
$data = array_merge($_GET, $_POST, $data);
echo json_encode(array(
'type' => $type,
'data' => $data['data']
));
?>
ajax.html:
<script src="http://libs.cncdn.cn/jquery/1.11.1/jquery.min.js"></script>
<script src="http://libs.cncdn.cn/jquery-ajaxtransport-xdomainrequest/1.0.3/jquery.xdomainrequest.min.js"></script>
<script>
$.ajax({
url: 'http://ndol.cn/api.php',
data: {
'data': 'zhao'
},
type: 'POST',
dataType: 'json'/*,
xhrFields:{
withCredentials:true
}*/
}).done(function(data) {
alert(JSON.stringify(data));
});
//alert($.support.cors);
</script>
jQuery ajax 跨域插件 jquery.xdomainrequest.min.js 的使用
最新推荐文章于 2024-11-05 21:55:28 发布