4

有没有办法等待 jQuery 的 getJSON 方法?

我想解析使用此函数接收的数据,如果包含特定字符串,则仅返回 false/true。但是由于异步数据处理,这似乎并不那么容易。这是一个代码片段:

contained = false;

$.getJSON(URL, function ( data ) {
    $.each( data, function( i, item ) {
        if ( item.Info.code == code ) contained = true;
    });
});

在这段代码之后,放置这段代码的函数返回“包含”值,这基本上是假的,因为 getJSON 还没有完成。

4

3 回答 3

8

正确的解决方案是不使其同步(这是可能的,但不建议这样做)。它正在适当地使用回调。异步编程需要习惯,但这是值得的。

代替:

function foo()
{
  ...

  contained = false;

 $.getJSON(URL, function ( data ) {
      $.each( data, function( i, item ) {
          if ( item.Info.code == code ) contained = true;
      });
  });

  // Do something with contained
}

做:

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
  });
}
于 2009-06-14T17:57:58.927 回答
6

您可以尝试执行同步请求,如下所示:

 $.ajax({
      type: "GET",
      url: "www.foo.com",
      data: data
      async: false,
      dataType: "json"
  });
于 2009-06-14T17:48:24.707 回答
5

谢谢您的回答。我只是将过程设置为同步:

$.ajaxSetup({'async': false});

之后,使用了我的代码。工作得很好!

更多 jQuery Ajax 选项在这里

于 2009-06-14T18:26:16.160 回答