简体   繁体   English

不可知方案/协议ajax调用

[英]Agnostic scheme / protocol ajax call

I would like to do an ajax call that adapts to current scheme ( http/https ). 我想做一个适应当前方案( http/https )的ajax调用。 What would be a really valid approach to this situation (both to xhr and xdr )? 对于这种情况(对于xhrxdr ),什么是真正有效的方法?

var xhr = new XMLHttpRequest(); // Or var xdr = new XDomainRequest
...
xhr.open("get", "//mydomain.com/api/v1/etc", true);
...

Or 要么

var xhr = new XMLHttpRequest();
...
xhr.open("get", window.location.protocol + "//mydomain.com/api/v1/etc", true);
...

Or.. anything else? 或者..还有什么?

Note: The question Making a protocol agnostic jquery ajax call does not mention the both cases XMLHttpRequest and XDomainRequest nor it provides a validated solution. 注意:进行 与协议无关的jquery ajax调用的问题未提及XMLHttpRequestXDomainRequest的两种情况,也未提供经过验证的解决方案。

This approach definitely will not work: 这种方法肯定行不通:

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

as this will send the request on the relative url, as there is no protocol mention here. 因为这将在相对网址上发送请求,因为此处没有提及协议。

This approach works on XMLHttpRequest : 这种方法适用于XMLHttpRequest

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

Important note that the XDomainRequest is obsolete and should not be used in your application as it will work only in IE 8-9 . 重要说明, XDomainRequest过时 ,不应在您的应用程序中使用,因为它仅在IE 8-9中有效

Great example of handling the various type of requests can be found here: 可以在这里找到处理各种类型请求的好例子

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM