作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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);
}
});
应该发生什么:从 PHP 中提取的 JSON 数组( [html] 和 [next] )。如果 [next] 设置为 0(当没有更多条目时)- while 循环停止,应该就是这样。
发生了什么:一切应该的,除了 - 当满足 while() 要求时(因此当 hasData 设置为 0 时) - 循环进入无限循环(并且它永远不断地请求最后一个条目......直到脚本变得“无响应” ”)
最佳答案
ajax
发送请求并在有响应时执行回调。所以发生的事情是:
因为它位于 while 循环内。您正在用请求堵塞脚本,并且服务器收到一堆它可能无法处理的请求。
编辑:抱歉,我错过了 async: false
。然而,这总是使浏览器无响应。最好的办法是使用 async: true
并在条件如此的情况下触发另一个,但只有在收到响应之后:
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,因此更方便的方法可能是:
(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
关于php - 当我在 JavaScript 中告诉它时,While 循环不会结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7064205/
我是一名优秀的程序员,十分优秀!