Ben*_*ikt 4 jquery json callback wait
有没有办法等待jQuery的getJSON方法?
我想解析数据,收到此函数,如果包含特定字符串,则返回false/true.但由于异步数据处理,这似乎并不那么容易.这是一段代码:
contained = false;
$.getJSON(URL, function ( data ) {
$.each( data, function( i, item ) {
if ( item.Info.code == code ) contained = true;
});
});
Run Code Online (Sandbox Code Playgroud)
在这个代码之后,放置此代码的函数返回'包含'值,whis基本上是false,因为getJSON还没有完成.
正确的解决方案不是使它同步(这是可能的,但不可取).它正在使用回调.异步编程需要习惯,但值得.
代替:
function foo()
{
...
contained = false;
$.getJSON(URL, function ( data ) {
$.each( data, function( i, item ) {
if ( item.Info.code == code ) contained = true;
});
});
// Do something with contained
}
Run Code Online (Sandbox Code Playgroud)
做:
function getContained(containedCallback)
{
$.getJSON(URL, function(data)
{
var contained = false;
$.each( data, function( i, item ) {
if ( item.Info.code == code ) contained = true;
});
containedCallback(contained);
}
);
}
function foo()
{
...
getContained(function(contained)
{
// Do something with contained
});
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试执行同步请求,如下所示:
$.ajax({
type: "GET",
url: "www.foo.com",
data: data
async: false,
dataType: "json"
});
Run Code Online (Sandbox Code Playgroud)
谢谢您的回答.我只是将进程设置为同步:
$.ajaxSetup({'async': false});
Run Code Online (Sandbox Code Playgroud)
之后,使用我的代码.工作得很好!
这里有更多jQuery Ajax选项