2014-11-21 82 views
0

我的網頁上有一個按鈕。如果用戶點擊它,任務將啓動並返回一個ID。我想用這個ID在另一個Ajax調用中檢查任務的進度,讓用戶知道任務是否完成。ajax內的Ajax調用

我都試過,但我不認爲這是正確的做法:

<script type="text/javascript"> 
$(document).ready(function() { 
    $('#get-user-transactions').click(function() { 

     $("#user-transactions").after("<p>Loading data</p>"); 

      $.ajax({ 
       url: "/start-task/", 
       dataType: "json", 
       success: function(data){ 
        if(data) { 

         var stateCheck = setInterval( 

          $.ajax({ 
           url: "/check-taskstate/"+data.task_id, 
           dataType: "json", 
           success: function(data){ 

            if (data.updated == 'true') { 
             clearInterval(stateCheck); 
             window.location.reload(); 
            } 
           } 

          })//ajax 

         , 1000); //stateCheck 


        }       

       } 

      })//ajax 

    }); 
}); 
</script> 

編輯

我更新了我的代碼,所以第一個URL也給出了JSON響應。但如果我嘗試我的代碼,我得到這個錯誤:

Uncaught SyntaxError: Unexpected identifier

+0

? – 2014-11-21 12:49:56

+0

不是這個代碼的工作?哪裏有問題? – 2014-11-21 12:50:49

+0

@ Mohamed-Yousef我需要每秒鐘檢查一下'/ check-taskstate/'來查看任務是否完成 – 2014-11-21 12:52:31

回答

1

由於setInterval()接受一個函數或代碼,但是你逝去的jqXHR對象,你一定是錯誤的那個。

func is the function you want to be called repeatedly

code in the alternate syntax, is a string of code you want to be executed repeatedly (using this syntax is not recommended for the same reasons as using eval())

使用

var stateCheck = setInterval(function(){ 
    $.ajax({ 
     url: "/check-taskstate/"+data.task_id, 
     dataType: "json", 
     success: function(data){ 

      if (data.updated == 'true') { 
       clearInterval(stateCheck); 
       window.location.reload(); 
      } 
     } 

    }); 
}, 1000); //stateCheck 
對你有什麼用的setInterval
+0

這樣做的竅門! – 2014-11-21 14:51:39