我从来不明白为什么人们总是间隔一定时间添加他们的AJAX请求,而不是让成功的AJAX呼叫自己来呼叫,而同时又冒着通过多个请求造成服务器负载沉重的风险,而不仅仅是在成功的呼叫返回后再发起另一个呼叫。
有鉴于此,我喜欢编写解决方案,其中AJAX调用仅在完成时调用它们自己,例如:
// set your delay here, 2 seconds as an example...var my_delay = 2000;// call your ajax function when the document is ready...$(function() { callAjax();});// function that processes your ajax calls...function callAjax() { $.ajax({ // ajax parameters here... // ... success: function() { setTimeout(callAjax, my_delay); } });}我希望这是有道理的!:)
更新:
在再次审查之后,已经引起我的注意,我需要澄清和解决的原始问题中的PHP代码中也存在一个问题。
尽管上面的脚本在创建AJAX调用之间的延迟方面非常有用,但是在原始帖子中将其添加到PHP代码后,该脚本将被
echo删除与SQL查询选择的行数一样多的次数,从而创建了多个函数相同的名称,并且可能同时进行所有AJAX调用…一点都不酷…
考虑到这一点,我提出了以下附加解决方案-
array使用PHP脚本创建一个,该脚本可以被Javascript一次消化一个元素,以实现所需的结果。首先,PHP构建Javascript数组字符串…
<?php include("includes/configuratie.php"); $strSQL = mysql_query("SELECt workerID FROM tWorkers ORDER BY workerID ASC"); // build the array for the Javascript, needs to be a string... $javascript_array = '['; $delimiter = ''; while($row = mysql_fetch_assoc($strSQL)) { $javascript_array .= $delimiter . '"'. $row['workerID'] .'"'; // with quotes $delimiter = ','; } $javascript_array .= ']'; // should create an array string, something like: // ["1","2","3"]?>接下来,Javascript来消化和处理我们刚刚创建的数组。
// set your delay here, 2 seconds as an example...var my_delay = 2000;// add your Javascript array here too...var my_row_ids = <?php echo $javascript_array; ?>;// call your ajax function when the document is ready...$(function() { callAjax();});// function that processes your ajax calls...function callAjax() { // check to see if there are id's remaining... if (my_row_ids.length > 0) { // get the next id, and remove it from the array... var next_id = my_row_ids[0]; my_row_ids.shift(); $.ajax({ cache : false, url : 'ajax2.php', data: "workerID=" + next_id, // next ID here! dataType : 'json', success : function(data) { // do necessary things here... // call your AJAX function again, with delay... setTimeout(callAjax, my_delay); } }); }}


