gpt4 book ai didi

php - 当我在 JavaScript 中告诉它时,While 循环不会结束

转载 作者:行者123 更新时间:2023-12-01 02:03:58 24 4
gpt4 key购买 nike

       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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com