而当我告诉它在JavaScript循环就不会结束 [英] While loop won't end when I tell it in JavaScript
问题描述
var hasData = '1';
while (hasData != 0) {
$.ajax({
url: '/ajax.php?updateRow='+hasData,
dataType: 'json',
async: false,
success: function(data) {
hasData = data.next;
$('.result').append(data.html);
}
});
会发生什么情况: JSON数组从PHP拉([HTML]和[下一步])。如果[下一页]设置为0(当没有更多的条目) - while循环停止,这应该是它
What should happen: JSON Array pulled from PHP ( [html] and [next] ). If [next] is set to 0 (when there are no more entries) - the while loop stops and that should be it.
什么happends: 一切应,除 - 当同时()要求得到满足(因此当hasData设置为0) - 环进入无限循环(和它保持请求的最后一个条目,永远...直到脚本变为不响应)
What happends: Everything that should, except - when the while() requirement is met (so when hasData is set to 0) - the loop enters into an infinite loop (and it keeps requesting the last entry, forever...until the script becomes "unresponsive")
推荐答案
AJAX
发送一个请求,并执行回调时,有一个回应。那么什么情况是:
ajax
sends a request and executes the callback when there is a response. So what's happening is:
- 消防的要求
- 在消防另一个请求
- 在消防另一个请求
- 在消防另一个请求
- ...
因为它是一个while循环中。你堵塞你的脚本了请求,服务器得到了一堆要求它有可能无法处理的。
because it's inside a while loop. You're clogging your script up with requests, and the server gets a bunch of requests which it probably cannot handle.
编辑:对不起,我错过了异步:假
。然而,每每让浏览器irresponsive。这样做将使用异步的最好的事情:真正的
和消防另一个,如果条件是这么说的,但只有在你得到的回应:
I'm sorry, I missed async: false
. However that always makes the browser irresponsive. The best thing to do would be using async: true
and fire another if the conditional says so, but only after you get the response:
function check() {
$.ajax({
url: '/ajax.php?updateRow='+hasData,
dataType: 'json',
async: true,
success: function(data) {
hasData = data.next;
$('.result').append(data.html);
if(hasData != 0) check(); // do it again
}
});
}
check(); // fire the first request
由于Spycho指出,因为你获取JSON,一个更方便的方法可能是:
As Spycho pointed out, since you're fetching JSON, a more convenient way might be:
(function() {
var fireRequest = function() { // this function is not available anywhere else,
// to avoid having this process running more than once
$.getJSON('/ajax.php', {updateRow: hasData}, function(data) {
hasData = data.next;
$('.result').append(data.html);
if(hasData != 0) fireRequest(); // do it again
});
};
fireRequest(); // start the process
})(); // call it
这篇关于而当我告诉它在JavaScript循环就不会结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!