2017-03-07 90 views
0

好的,這是我的問題。我正在使用使用分頁的API。我保持循環,直到返回的響應是一個空白數組。但是,這不起作用,代碼只是掛起。每一個循環,我增加頁面變量來獲取下一頁。while循環與jQuery AJAX分頁

// Function to get a list of 50 assignments. 
function getAssignments(token, instuctureSubdomain, course, page, callback) { 
    var settings = { 
     "async": true, 
     "crossDomain": true, 
     "url": "https://" + instuctureSubdomain + ".instructure.com/api/v1/users/self/courses/" + course + "/assignments?per_page=50&page=" + page, 
     "method": "GET", 
     "headers": { 
     "authorization": "Bearer " + token, 
     "cache-control": "no-cache" 
     } 
    } 

    $.ajax(settings).done(function (response) { 
     callback(response); 
    }); 
}; 

var loop = true; 
var page = 1; 
while (loop) { 
    getAssignments(token, instuctureSubdomain, item.id, page, function (response) { 
     if (response.length == 0) { 
// End the loop because the response returned a blank array. 
      loop = false; 
     } else { 
      response.forEach(function (item) { 
// Add the assignment to an array... 
      }); 
      page++ 
     }; 
    }); 
}; 
+0

您是否嘗試過使用console.log來查看您獲得的結果?我會建議從那裏開始。 – Neil

+0

如果分頁顯示10每次可以說,並且你總共有48個結果,那麼最終的回覆長度是8而不是0? – Harry

+0

@Harry真,但循環應該再次運行,然後API將返回一個空數組,停止循環。 – juliancz

回答

0

下面是我將如何寫它。它不會延遲/凍結您的網頁並提供大量請求,並幾乎同步地調用它。

<script> 

function loop (i) { 
    $.get("http://example.com/api/" + i + ".php", function (data) { 
     array = process(data); 
     if (array.length > 0) { 
      loop(i + 1); 
     } 
    }); 
} 

loop(1); 

</script>