jquery getJSON函数计时问题
我认为我的程序正在跳过 JSON 调用的结果。 是否可以在此处创建一个闭包函数或让程序等待 JSON 调用返回?
function username_not_duplicate(username) {
var function_name = "get_username";
var parameters = [username];
var url = "/get_functions.php?function_name=" + function_name + "¶meters=" + parameters;
$.getJSON(url, function(user_name) {
if (user_name == true) {
return true;
}
});
return false;
}
I think my program is skipping result of JSON call.
Is it possible to make a closure function here or make the program wait for JSON call to return?
function username_not_duplicate(username) {
var function_name = "get_username";
var parameters = [username];
var url = "/get_functions.php?function_name=" + function_name + "¶meters=" + parameters;
$.getJSON(url, function(user_name) {
if (user_name == true) {
return true;
}
});
return false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
$.getJSON()
API 调用是异步的。您可以通过以下方式使用$.ajax()
使其同步:The
$.getJSON()
API call is asynchronous. You can make it synchronous by using$.ajax()
this way:Drew 的答案近乎完美,只是少了一个括号和 IE 的逗号。
Drew's answer is nearly perfect, just missing one bracket and comma for IE.
另一种选择是使用回调函数并将其传递给执行 getJSON 的函数,如下所示:
这样您的回调函数将在 getJSON 调用结束时被调用。
Another choice is to use a call back function and pass it to the function that executes the getJSON as:
This way your callback function will be called at the end of the getJSON call.
是的,
username_not_duplicate
只是立即返回false
,因为getJSON
是异步的(即非阻塞)。return true
语句仅从响应处理程序返回true
。通常,您不应该执行您想要实现的此类阻塞调用。我想您可以考虑在全球某个地方记住请求的状态。
Yeap,
username_not_duplicate
just returnsfalse
immediately becausegetJSON
is asynchronous (ie non-blocking). Thereturn true
statement just returnstrue
from the response handler.Normally, you shouldn't do such a blocking calls you're trying to achieve. I suppose you can consider remembering of a state of the request somewhere globally.