1

我想做一个适应当前方案(http/https)的ajax调用。对于这种情况,什么是真正有效的方法(toxhrxdr)?

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);
...

或者..还有什么?

注意:Making a protocol agnostic jquery ajax call的问题没有提到这两种情况XMLHttpRequestXDomainRequest也没有提供经过验证的解决方案。

4

1 回答 1

2

这种方法肯定行不通:

xhr.open("get", "//mydomain.com/api/v1/etc", true);

因为这将在相对 url 上发送请求,因为这里没有提到协议。

这种方法适用于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="&quot;+RequestHelper.GatewayURL+&quot;" 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); } 
        }); 
}
于 2015-02-20T12:27:26.910 回答