开发者

How can I get returning data from jquery ajax request?

function isNewUsername(str){
    var result;
    $.post('/api/isnewusername', 
            {username:str},
            function(data) {
          开发者_开发技巧      result = data.result;
            }, 
            "json");
    return result;
}

So , my problem is very simple but I can not figure it out . I want to access result from the isnewusername function . I am very curious about answer because I spent 1 hour on it . Thank you


It cannot be done the way you're doing it, as ajax queries are asynchronous (meaning, they don't block, and the result will not come instantly, it'll come when the server actually responds). You'll have to call another function with the results (or otherwise, only do something with the results once they are actually available).

For instance:

function isNewUsername(str){
    $.post('/api/isnewusername', 
            {username:str},
            function(data) {
                someOtherFunction(data.result);
            }, 
            "json");
}


As a quick note when you use the jQuery post function you are using a shorthand form of the jQuery ajax function which means you are doing an asynchronous call. Therefore only on a successful response is jQuery going to call your function and put the result from your server side call in the data parameter of your success callback.

To illustrate:

function isNewUsername(str){
    $.post('/api/isnewusername', 
            {username:str},
            function(data) {
                alert(data.result);
            }, 
            "json");
}

That said you can change your code to specify a synchronous callback but that has the potential to lock the users browser until the request is returned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜