ajax函数的延迟调用,在重复的jQuery / Ajax函数中设置延迟

小编典典

我从来不明白为什么人们总是间隔一定时间添加他们的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数组字符串…

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);

}

});

}

}

2020-07-26

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值