[英]Agnostic scheme / protocol ajax call
我想做一个适应当前方案( http/https
)的ajax调用。 对于这种情况(对于xhr
和xdr
),什么是真正有效的方法?
var xhr = new XMLHttpRequest(); // Or var xdr = new XDomainRequest
...
xhr.open("get", "//mydomain.com/api/v1/etc", true);
...
要么
var xhr = new XMLHttpRequest();
...
xhr.open("get", window.location.protocol + "//mydomain.com/api/v1/etc", true);
...
或者..还有什么?
注意:进行 与协议无关的jquery ajax调用的问题未提及XMLHttpRequest
和XDomainRequest
的两种情况,也未提供经过验证的解决方案。
这种方法肯定行不通:
xhr.open("get", "//mydomain.com/api/v1/etc", true);
因为这将在相对网址上发送请求,因为此处没有提及协议。
这种方法适用于XMLHttpRequest
:
xhr.open("get", window.location.protocol + "//mydomain.com/api/v1/etc", true);
重要说明, XDomainRequest
已过时 ,不应在您的应用程序中使用,因为它仅在IE 8-9中有效 。
可以在这里找到处理各种类型请求的好例子 :
if(window.XDomainRequest){
if(protocol == "http:"){
if(RequestHelper.Busy){
setTimeout(function(){
RequestHelper.sendRequest(url,success,$);
},50);
} else {
RequestHelper.Busy = true;
$("body").append("<iframe id="ajaxProxy" style="display: none;" src=""+RequestHelper.GatewayURL+"" width="320" height="240"></iframe>");
$("#ajaxProxy").load(function(){
ajaxProxy.postMessage(url,"*");
//...
});
}
} else {
var xdr = new XDomainRequest();
xdr.open("get", url);
//...
}
} else {
$.ajax({
type: "GET",
url: url,
dataType: "html",
async:true, success:
function (response){
success(response); }
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.