jus*_*ris 2 javascript php ajax jquery json
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);
}
});
Run Code Online (Sandbox Code Playgroud)
应该发生什么:从PHP([html]和[next])拉出JSON数组.如果[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
Run Code Online (Sandbox Code Playgroud)
正如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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
321 次 |
| 最近记录: |