2011-01-20 119 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); 
               } 
             }); 
          } 
      });