简体   繁体   English

如何从jquery ajax请求中返回数据?

[英]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 . 我想从isnewusername函数访问结果。 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). 由于ajax查询是异步的(因此,它们不会阻塞,并且结果不会立即出现,而是在服务器实际响应时出现),因此无法按照您的方式进行操作。 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. 作为快速注释,当您使用jQuery post函数时,您正在使用jQuery ajax函数的简写形式,这意味着您在进行异步调用。 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. 因此,只有在成功响应后,jQuery才会调用函数并将服务器端调用的结果放入成功回调的data参数中。

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. 也就是说,您可以更改代码以指定同步回调,但是有可能锁定用户浏览器,直到返回请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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