jQuery ajax 跨域插件jquery.xdomainrequest.min.js的使用方法
作者:七汐爱椰枣
jQuery XDomainRequest 是一个利用 XDomainRequest 对象为 IE8、IE9 实现跨域资源共享(CORS - Cross Origin Resource Sharing)的 jQuery 插件。
官方网址:https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
约束:
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'); 时,各浏览器跨域支持情况有差异。
With at least jQuery version 1.5, just include the jquery.xdomainrequest.min.js script into your page, then make your AJAX call like you normally would:
// GET
$.getJSON('http://jsonmoon.jsapp.us/').done(function(data) {
console.log(data.name.first);
});
// POST
$.ajax({
url: 'http://frozen-woodland-5503.herokuapp.com/cors.json',
data: 'this is data being posted to the server',
contentType: 'text/plain',
type: 'POST',
dataType: 'json'
}).done(function(data) {
console.log(data.name.last);
});更新说明
1.0.2 - added RequireJS AMD module support
1.0.3 - added CommonJS and Bower support
1.0.4 - support protocol-relative URLs, use peerDependencies in package.json
应用实例
代码:
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>其它网友的补充
IE8&IE9上不能使用XMLHttpRequest来通过cors来处理跨域,他们提供了一个特别的对象XDomainRequest来处理CORS跨域通讯。
可以参考:CORS
它的回掉函数和XMLHttpRequest基本一致,这里不重叙。
下面只要说几个坑点:
1.要保持请求协议和当前访问网站的协议一致。
例如:浏览器地址栏的协议是https,那么你的XDomainRequest只能发起https请求,否则“拒绝访问”
2. 如果你使用vue同时使用CORS,想要兼容IE8!不用多想了。
XDomainRequest是支持IE8 CORS的,但是vue不支持,这个锅并不是XDomainRequest的,XDomainRequest不背(●'◡'●)。
贴代码:
return new Promise((resolve, reject) => {
let appliance = new window.XDomainRequest()
appliance.onprogress = function () { }; // no aborting
appliance.ontimeout = function () {
// alert("timeout")
reject({ eror: "timeout" });
}; // "
appliance.onload = function (e) {
// do something with appliance.responseText
// alert("onload" + appliance.responseText)
resolve(appliance.responseText);
};
appliance.onerror = function (e, b) {
// error handling
// alert("error" + JSON.stringify(e) + JSON.stringify(b))
reject({ eror: e });
};
//appliance.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
appliance.withCredentials = true; // to support sending cookies with CORS
appliance.open("POST", axios.defaults.baseURL + url);
appliance.send(dataToString);
});到此这篇关于jQuery ajax 跨域插件jquery.xdomainrequest.min.js的使用方法的文章就介绍到这了,更多相关jQuery XDomainRequest内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
