简体   繁体   中英

jQuery cross-domain request returns 'undefined'

After reading various examples on stackoverflow I wrote this function :

function showGetResult(crossDomainUrl) {
    $.ajax({
        url: crossDomainUrl,
        type : 'GET',
        crossDomain: true,
        success: function (data) {
            debug(data);
            return data;
        }
    });
}

and called it using this

alert(showGetResult(crossDomainUrl));

But all I get is ' undefined ', this is being used in a web-browser extension inside a content-script.

This is because the Ajax request runs asynchronously. The return data doesn't do anything. You could change it to (updated to reflect the request in the comments to be able to download a script):

function showGetResult(crossDomainUrl) {
    return $.ajax({
        url: crossDomainUrl,
        type : 'GET',
        dataType: 'script',
        crossDomain: true
     });
}

showGetResult('http://code.jquery.com/ui/1.10.3/jquery-ui.js')
    .done(function(data) {
        alert("success: " + data);
    })
    .fail(function(jqXHR, textStatus, ex) {
        alert("failed: " + textStatus);
    });

For the call actually to work cross-domain, you will need to use jsonp or script. Read this wiki for more information about Same-origin policy. Refer to this answer for more information about using jsonp.

The code above will inject the downloaded jscript in the dom and execute it.

The $.ajax() set up the query, and return immediately, so the function returns before the request is completed. Specify a function to call on completion of the query using success .

function showGetResult(crossDomainUrl) {
    $.ajax({
        url: crossDomainUrl,
        type : 'GET',
        crossDomain: true,
        success: showData
    });
}

function showData(data){
    debug(data);
    return data;
}
showGetResult(crossDomainUrl);

see http://jsfiddle.net/5J66u/8/ - (updated to specify jsonp and a better URL for it)

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