Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm work on script that will send ajax post to another page, i need to make two for loops before send ajax request with time out, one of them send successcfully but when make another loop it send all requests same time and make the server down:(我正在处理将ajax发布发送到另一页的脚本,我需要在超时之前发送ajax请求之前进行两个for循环,其中一个成功发送,但是在进行另一个循环时它将同时发送所有请求并使服务器下:)

$("#me").on("click", function (event) { event.preventDefault(); var lines = $('#emails').val().split(' '); var sendToServer = function(lines, index){ item = lines[index]; if (item.trim().length != 0){ for(idd = 1; idd <= 100; idd++){ $.ajax({ type: 'POST', url: 'inc/save.php', data: { users : lines[index] , id : idd }, success: function(msg){ $('#result').append(msg); if (index < lines.length) { setTimeout( function () { sendToServer(lines, index+1); }, 5000 // delay in ms ); } } }); } } else { sendToServer(lines, index+1); } }; sendToServer(lines, 0); });   ask by Mohamed Aldanaf translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
182 views
Welcome To Ask or Share your Answers For Others

1 Answer

This code will delay a specified amount of time between every request(此代码将在每个请求之间延迟指定的时间量)

$("#me").on("click", function (event) { event.preventDefault(); var lines = $('#emails').val().split(' '); var requestDelay = 5000; var sendToServer = function (index) { item = lines[index]; if (item.trim().length != 0) { var max = 100; var sendOne = function (idd) { $.ajax({ type: 'POST', url: 'inc/save.php', data: { users: lines[index], id: idd }, success: function (msg) { $('#result').append(msg); if (idd <= max) { setTimeout(sendOne, requestDelay, idd + 1); } else { if (index < lines.length) { setTimeout(sendToServer, requestDelay, index + 1); } } } }); }; sendOne(1); } }; sendToServer(0); }); It's set to 5000 requestDelay - but you could probably reduce that significantly(设置为5000 requestDelay但您可能会大大减少) A "modern" code version using async/await and the fact that jquery.ajax returns a thenable(使用async / await的“现代”代码版本以及jquery.ajax返回thenable的事实) $("#me").on("click", async function (event) { event.preventDefault(); const requestDelay = 5000; const wait = result => new Promise(resolve => setTimeout(resolve, requestDelay, result)); const getIdd = async users => { for ( let id = 1; id <= 100; ++id) { const msg = await $.ajax({ type: 'POST', url: 'inc/save.php', data: { users, id } }); $('#result').append(msg); await wait(); } }; const lines = $('#emails').val().split(' '); for (let line of lines) { await getIdd(lines); } });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...