2011-01-20 86 views
0

我有一个json的两个Ajax调用。 第一个帮助我获得globalVar值。 第二个接受此值,将其传递给远程URL中的参数,然后返回结果。jQuery同步问题

var globalVar = ""; 

var firstRemoteUrl = "http://example.com/some/json"; 
     $.ajax({ 
      type: "GET", 
      url: firstRemoteUrl , 
      dataType: 'jsonp', 
      success: function (data) { 
       globalVar = data; 
      } 
     }); 


var secondRemoteUrl = "http://example.com/another/json?var = " + globalVar; 
     $.ajax({ 
      type: "GET", 
      url: secondRemoteUrl , 
      dataType: 'jsonp', 
      success: function (data) { 
       alert(data); 
      } 
     }); 

与这些类型的调用的问题是,第二AJAX调用不会等待,直到第一个实现它的呼叫。 因此,有时globalVar是空的。因此,第二次电话将不会正常结束。

我试过async set ti false但是,正如在jquery文档中指出的那样,jsonp数据类型忽略同步调用。

有没有这个问题的解决方法?

谢谢,

问候。

+0

我发现了另一个workarround通过添加 “等待”: 功能pausecomp(米利斯) { \t变种日期=新日期(); \t var curDate = null; \t do {curDate = new Date(); (curDate-date Zakaria 2011-01-21 10:36:42

回答

1

您可以将第二个电话放在第一个电话的回叫中。这有点乱,但应该完成工作。例如:

$.ajax({ 
type: "GET", 
url: "http://example.com/some/json", 
dataType: 'jsonp', 
success: function(data) { 
    $.ajax({ 
    type: "GET", 
    url: "http://example.com/another/json?var = " + data, 
    dataType: 'jsonp', 
    success: function(result) { 
    alert(result); 
    } 
    }); 
} 
}); 
1

将第二个ajax调用放在第一个ajax调用的成功回调函数中。

var firstRemoteUrl = "http://example.com/some/json"; 
    $.ajax({ 
     type: "GET", 
     url: firstRemoteUrl , 
     dataType: 'jsonp', 
     success: function (data) { 
      globalVar = data; 
      secondRemoteUrl = "http://example.com/another/json?var = " + globalVar; 
          $.ajax({ 
            type: "GET", 
            url: secondRemoteUrl , 
             dataType: 'jsonp', 
             success: function (data) { 
                alert(data); 
               } 
             }); 
          } 
      });