的$。员额()调用的返回值 [英] Return value of $.post() call
问题描述
我有一个jQuery $。员额功能LIK这样:
I have a jquery $.post function lik so:
$.post('/test',json_data, function(data) {
result=data
});
这个功能实际上是被以验证使用......因此,它的返回值(数据)包含true或false。但该值不被存储在变量结果。据我所知,这是因为后发出异步调用,因此它一点儿也不等待响应。我想问的是,有一些解决方法吗?或者可以这样调用进行同步不知何故?
this function is actually being used in an validation...So it the return value(data) contains true or false. But this value is not being stored in the variable 'result'. I understand that this is because post makes an asynchronous call and hence it does'nt wait for the response. What I want to ask is, is there some workaround for this? or can this call be made synchronous somehow??
推荐答案
这被认为是不好的做法,但在的异步参数: //api.jquery.com/jQuery.ajax/相对=nofollow> $。阿贾克斯()
,你可以设置为假
并等待同步的结果是:
This is considered a bad practice but there is an async
parameter in $.ajax()
that you can set to false
and wait synchronously for a result:
var result;
$.ajax({
type: 'POST',
url: '/test',
data: json_data,
async: false,
success: function(data) {
result=data;
},
dataType: 'application/json'
});
//result available here
有一个更地道,但在这种情况下略显不太方便,就采取回调的优点是:
A more idiomatic, although slightly less convenient in this case, would be to take advantage of callbacks:
function validate(okCallback, errorCallback) {
$.post('/test',json_data, function(data) {
if(data) {
okCallback();
} else {
errorCallback();
}
});
}
validate(
function() {
//proceed
},
function() {
//display validation error
}
}
这篇关于的$。员额()调用的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!