如何从jQuery Deferred对象取值并在所有Ajax完成后执行函数
Let's fix this step by step. The core issue with your initial attempt was that you were pushing functions (not actual promises) into your array, and you weren't properly capturing the AJAX promises returned by each request. Here's how to do it right:
Corrected Code
// Initialize an array to hold all AJAX promises const promises = []; // Loop through each existing transaction table $('.table-transactions').each(function() { const $table = $(this); const tableTdId = $table.find('td').attr('id'); // Get "table1", "table2", etc. const scriptId = tableTdId.replace('table', ''); // Extract the number for the URL // Create the AJAX request and store its promise const ajaxPromise = $.ajax({ url: `path/to/script/${scriptId}`, type: 'post', dataType: 'json', data: { 'data': 'something' }, success: function(response) { // Update ONLY the span in the current table $table.find('.test').text(response); } }); // Add the AJAX promise to our array promises.push(ajaxPromise); }); // Wait for all promises to resolve, then run our post-processing function $.when.apply($, promises).then(function(...allResponses) { // This code runs AFTER all spans are updated successfully console.log('All span content has been loaded!'); console.log('Responses from all requests:', allResponses); // Your custom post-processing logic here });
Breaking Down the Solution
1. Capturing AJAX Promises
Every $.ajax() call returns a promise automatically. Instead of creating separate if blocks for each table, we loop through existing tables, generate the correct URL for each, and push the AJAX promise directly into our promises array. This ensures we're tracking every in-flight request.
2. Answering Your Questions
How to return text values to Deferred objects?
You don't need to manually create Deferred objects here—$.ajax() handles this for you. The promise resolves with the response data from the server. If you want to collect all responses, the ...allResponses parameter in the .then() callback will contain an array of every AJAX response in the order the requests were made.
How to use Promises for subsequent operations?
$.when.apply($, promises) waits for all promises in the array to resolve. The .then() method attached to it will execute only after every AJAX request has completed successfully. This is where you put your code that needs to run once all spans are filled.
Handling Failures (Optional)
If you want your post-processing function to run even if some requests fail, modify each AJAX promise to always resolve (instead of rejecting on error):
const ajaxPromise = $.ajax({ // ... existing AJAX options }) .done(function(response) { $table.find('.test').text(response); }) .fail(function() { $table.find('.test').text('Failed to load'); }) // Convert rejected promise to resolved with status info .then( response => ({ success: true, data: response }), () => ({ success: false, data: null }) );
Now the .then() block will run regardless of individual request outcomes, and you can check the success status of each request in allResponses.
Content of the question来源于stack exchange,提问作者Peter Griffin

