简体   繁体   中英

Sending cross-domain ajax requests without jQuery

I have the following code:

function ajax(callback, requestString){
    console.log("basic ajax sending");
    var xmlhttp;
    // compatible with IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            callback(xmlhttp.responseText); //we got a response    
        }
    }

    xmlhttp.open("GET", requestString, true);
    xmlhttp.send();

}
//Here: code to be able to use that function repeatedly.

it works great if used on my node.js server's domain, problem is that I am developing an API, and requests have to be sent cross-domain. These requests(requestString) are just one string that is formatted something in the likes of: " http://example.com/r?a=a " + "&b= b" if that matters. I get the following error: XMLHttpRequest cannot load. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. I did see a solution with jQuery and jsonP but I don't want to shove jQuery to my clients, so I have to find a good solution... Thank you for your time!

But jsonP can work without jQuery. For example:

var CallbackRegistry = {};

function scriptRequest(url, onSuccess, onError) {
    var scriptOk = false;
    // generating JSONP function name
    var callbackName = 'cb' + String(Math.random()).slice(-6);
    // add name in url
    url += ~url.indexOf('?') ? '&' : '?';
    url += 'callback=CallbackRegistry.' + callbackName;
    CallbackRegistry[callbackName] = function (data) {
        scriptOk = true;
        delete CallbackRegistry[callbackName];
        onSuccess(data);
    };
    function checkCallback() {
        if (scriptOk) return;
        delete CallbackRegistry[callbackName];
        onError(url);
    }
    var script = document.createElement('script');
    // for IE
    script.onreadystatechange = function () {
        if (this.readyState == 'complete' || this.readyState == 'loaded') {
            this.onreadystatechange = null;
            setTimeout(checkCallback, 0);
        }
    }
    script.onload = script.onerror = checkCallback;
    script.src = url;
    document.head.appendChild(script);
}

Now you can get response through cross domain just call

function afterSuccess(data) {
    alert('Success' + data);
}
function afterError(data) {
    alert('Error' + data);
}

scriptRequest(url, afterSuccess, afterError);

Well, on the server side you could change the Access-Control-Allow-Origin for the end point to Access-Control-Allow-Origin: * , ...note this will match anything. Depending on your server framework there is definitely a method to whitelist certain urls to access your endpoint. Hope that helps

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