简体   繁体   中英

Agnostic scheme / protocol ajax call

I would like to do an ajax call that adapts to current scheme ( http/https ). What would be a really valid approach to this situation (both to xhr and xdr )?

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.

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 :

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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