如何用jQuery实现每秒一个AJAX请求?现有代码未生效
解决每秒发起一个AJAX请求的问题
你的代码之所以没实现请求间隔,核心问题是三层$.each循环会瞬间把所有请求的setTimeout都注册完成,而且所有延迟时间都设为1000ms,结果就是1秒后所有请求会同时触发,完全没有间隔。
下面给你两个实用的解决方法:
方案一:整理请求项为一维数组,按索引设置递增延迟
先把嵌套结构里的所有product提取到一个一维数组中,然后遍历这个数组时,给每个请求的延迟时间设置为索引值 × 1000,这样第1个请求立刻发起,第2个1秒后发起,第3个2秒后发起……以此类推,就能保证严格的每秒一个请求。
代码示例:
// 先把所有需要请求的product整理成一维数组 const allProducts = []; $.each(added_collections, function(index, collection) { $.each(collection, function(index1, page) { $.each(page, function(index2, product) { allProducts.push(product); }); }); }); // 遍历数组,按索引设置递增延迟 allProducts.forEach(function(product, idx) { setTimeout(function() { $.ajax({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, type: "POST", url: '/get_data', dataType: "json", data: meta_data, // 注意:这里要根据当前product调整meta_data,避免所有请求发相同数据 success: function(data) { console.log(data); }, error: function(data){ console.log(data); } }); }, idx * 1000); // 关键:用索引乘以1000,实现每个请求延迟递增1秒 });
方案二:递归发起请求(适合需要等待上一个请求完成的场景)
如果你不仅要间隔1秒,还想确保上一个请求完成(无论成功或失败)后再发起下一个,避免请求堆积,可以用递归的方式:
const allProducts = []; $.each(added_collections, function(index, collection) { $.each(collection, function(index1, page) { $.each(page, function(index2, product) { allProducts.push(product); }); }); }); let currentIndex = 0; function sendNextRequest() { if (currentIndex >= allProducts.length) return; // 所有请求发完就终止 const product = allProducts[currentIndex]; $.ajax({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, type: "POST", url: '/get_data', dataType: "json", data: meta_data, // 记得根据当前product调整请求数据 success: function(data) { console.log(data); }, error: function(data){ console.log(data); }, complete: function() { // 请求完成后,过1秒发起下一个请求 currentIndex++; setTimeout(sendNextRequest, 1000); } }); } // 启动第一个请求 sendNextRequest();
内容的提问来源于stack exchange,提问作者Aleks Per
相关产品推荐
相关产品推荐

