Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

Is there a way to return a value (xml in my case) from a JQuery Ajax Call

I guess I am missing something quite fundamental and maybe someone can fill me in. I have used an ajax call from two places. So now I am trying to reuse that call by making the call return a value. It looks something like this:

function getInfo()
{
    $.ajax({
    type: "GET",
    url: "../ajax.aspx?action=getInfo&id=4", 
        dataType: "xml",
    async: false,
    error: function() {
        alert("Something went wrong.");
    }, 
    success: function(xml) {
            // Do some extra work here
    $(xml).find("room").each(function() {
        // Do something based on the xml
    }); 
    // Something else can use this XML so return it too.
            // Why does this return not work???
            return xml;
    } 
});
}

So somewhere else in the script i am calling that function

var xml = getInfo();
// Try do something with it now but it says that it is undefined

and when i say it says it is undefined I am talking about Firebug.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Turning off the asynchronous functionality is imho not a very good AJAX programming style. You will loose a lot of the advantages of this technology. From the jquery documentation:

Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

If you need to do it anyway: $.ajax returns the XMLHTTPRequest object it creates. And your getInfo method should return that as well, so your code should be modified like this:

function getInfo()
{
    return $.ajax({
    type: "GET",
    url: "../ajax.aspx?action=getInfo&id=4", 
        dataType: "xml",
    async: false,
    error: function() {
        alert("Something went wrong.");
    }, 
    success: function(xml) {
            // Do some extra work here
        $(xml).find("room").each(function() {
            // Do something based on the xml
        });     
        // Something else can use this XML so return it too.
            // Why does this return not work???
            return xml;
    } 
}).responseText;
}


var xml = getInfo();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...