如何用jQuery循环处理文本域行?实现每次批量发送10行邮箱数据
Solution: Send Emails in Batches of 10
Got it, let's tweak your existing script to handle sending emails in batches of 10 instead of all at once. This approach is gentler on your server and avoids potential timeouts or request limits. Here's the updated code with explanations:
$(document).ready(function() { $("#check").on("click", function(event) { event.preventDefault(); // Split email text into an array, and filter out empty lines to avoid invalid entries let allEmails = $('#emails').val().split('\n').filter(line => line.trim() !== ''); const batchSize = 10; let currentBatchNumber = 0; // Recursive function to send one batch at a time function sendNextBatch() { // Calculate the range for the current batch const startIndex = currentBatchNumber * batchSize; const endIndex = startIndex + batchSize; const batchToSend = allEmails.slice(startIndex, endIndex); // Exit if there are no more emails to process if (batchToSend.length === 0) { $('#result').append('<p>✅ All email batches have been sent!</p>'); return; } // Send the batch via AJAX $.ajax({ type: 'POST', url: 'send.php', data: { email: batchToSend, // Pass the 10-email batch instead of all lines mail_from: $('#mail_from').val(), attach: $('#attach').val(), mail_name: $('#mail_name').val(), message: $('#message').val(), title: $('#title').val() }, success: function(response) { // Update the result area with batch status $('#result').append(`<p>Batch ${currentBatchNumber + 1} processed: ${response}</p>`); currentBatchNumber++; // Trigger the next batch only after the current one succeeds sendNextBatch(); }, error: function(xhr, status, errorMsg) { $('#result').append(`<p>❌ Error with batch ${currentBatchNumber + 1}: ${errorMsg}</p>`); // Optional: Uncomment the lines below to continue sending batches even if one fails // currentBatchNumber++; // sendNextBatch(); } }); } // Start the batch sending process sendNextBatch(); }); });
Key Improvements & Notes:
- Empty Line Filtering: The
filtermethod removes any blank lines from your email list, so you don't send invalid or empty entries to your server. - Serial Batch Sending: We use a recursive function to send one batch at a time (only after the previous batch succeeds). This prevents overwhelming your server with concurrent requests.
- Progress Feedback: The result area shows status updates for each batch, so you can track which batches succeeded or failed.
- Error Handling: You can choose whether to stop sending batches if one fails (default behavior) or continue processing the rest (uncomment the lines in the error callback).
Backend Check:
Make sure your send.php script is set up to handle an array of emails. In PHP, you can access the batch using $_POST['email'] (it will be an array of 10 or fewer email addresses).
内容的提问来源于stack exchange,提问作者Mohamed Aldanaf
相关产品推荐
相关产品推荐

