问题描述
function isNewUsername(str){
var result;
$.post('/api/isnewusername',
{username:str},
function(data) {
result = data.result;
},
"json");
return result;
}
所以,我的问题很简单,但我想不通.我想从 isnewusername 函数访问结果.我对答案很好奇,因为我花了 1 小时在上面.谢谢
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
推荐答案
作为使用 jQuery post 函数 您正在使用 jQuery ajax 函数的简写形式 这意味着您正在进行异步调用.因此,只有在成功响应时,jQuery 才会调用您的函数,并将服务器端调用的结果放入成功回调的 data
参数中.
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.
举例说明:
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.
这篇关于如何从 jquery ajax 请求中获取返回数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!