2016-01-29 47 views
1

我有一個用例,我希望我的第一個請求到服務器應立即(同步方式)發生。 基於這種情況,我會顯示一些信息。然後我需要異步輪詢相同的請求(ajax)。 我有異步部分的解決方案。但第一個操作,我怎麼能在jQuery中實現這一點。 兩者都是相同的請求。建議如果有其他方法來實現這一點。jquery - 首先獲取請求同步和後續異步

(function poll() { 
      setTimeout(function() { 
       $.ajax({ 
        url: "server script path", 
        type: "GET", 
        success: function(data) { 
         console.log("polling"+data); 
         if(data.is_running === false){ 
          console.log("stop polling"); 
          $("#overlay").show(); 
         } 
        }, 
        dataType: "json", 
        complete: poll, 
        timeout: 2000 
       }) 
      }, 50000); 
     })(); 

感謝,

+0

ajax請求本質上是異步的。把你的ajax調用放入一個函數中,立即調用該函數並顯示消息。另外,如果你想輪詢,你不應該使用setInterval而不是setTimeout? –

+0

即使我把我的ajax變成了一個方法,這個調用是異步的。 – JavaUser

+1

我看到,有一個名爲「async」的jquery ajax設置屬性,您可以將其設置爲false。它會阻止瀏覽器,直到請求完成。 –

回答

1
(function poll(synchronous) { 
    setTimeout(function() { 
     $.ajax({ 
      url: "server script path", 
      type: "GET", 
      success: function(data) { 
       console.log("polling"+data); 
       if(data.is_running === false){ 
        console.log("stop polling"); 
        $("#overlay").show(); 
       } 
      }, 
      dataType: "json", 
      complete: poll, 
      timeout: 2000, 
      async: !synchronous 
     }) 
    }, 50000); 
})(true); 
0

所有你需要做的就是在你的第一個請求async屬性設置爲false

$.ajax({ 
    url: "your url here", 
    type: "GET", 
    success: onSuccess, 
    dataType: "json", 
    async: false, 
    complete: poll //this will start your polling 
    //Everything else 
}); 

您可以閱讀文檔here$.ajax和它的屬性。將async設置爲false會使其成爲同步請求。

此外,如果您想要輪詢服務器,您應該使用setInterval而不是setTimeout作爲Eric Guan在評論中提到的。

編輯:關於第二個想法,我看到你在ajax請求完成時調用poll。這可能比setInterval更好,這取決於您的使用情況。