调用多个ajax调用

$.ajax({ url: "", jsonpCallback: 'item', contentType: "application/json", dataType: 'jsonp', success: function(data) { console.log(data); var markup = ""; $.each(data.list, function(i, elem) { dbInsert(elem['itemCode'], elem['description'], elem['price']); }); }, error: function(request, error) { alert(error); } }); 

我有以上类型的不同的ajax调用与不同的url。 我怎样才能一个接一个地运行每个Ajax调用?

你可以做这样的事情。

 $('#button').click(function() { $.when( $.ajax({ url: '/echo/html/', success: function(data) { alert('one is done') } }), $.ajax({ url: '/echo/html/', success: function(data) { alert('two is done') } }) ).then( function(){ alert('Final Done'); }); }); 

小提琴

跟踪仍然要发送的url,并拥有一个ajax请求的成功内联function去调用下一个。

 var urls = [...]; var runNextAjax = function() { var url = urls.pop(); $.ajax({ url: url, ... other settings, as before ... success: function(data) { ... do what you want with the data ... if (urls.length > 0) runNextAjax(); }, error: function(req, err) { ... do what you want with the error ... if (urls.length > 0) runNextAjax(); } }); }; // Start the sequence off. runNextAjax(); 

上面的代码在数据到达时作用于数据,如果你想要将它们全部缓存并在最后对它进行操作,将每个结果存储在一个数组中,然后在最后调用的函数中处理数组:

 var dataAccumulator = []; var displayAllData = function() { for (int i = 0; i < dataAccumulator.length; ++i) { var data = dataAccumulator[i]; ... process the data into HTML as before ... } }; var urls = [...]; var runNextAjax = function() { var url = urls.pop(); $.ajax({ url: url, ... other settings, as before ... success: function(data) { // Store the data we received dataAccumulator.push(data); if (urls.length > 0) runNextAjax(); else displayAllData(); }, error: function(req, err) { ... do what you want with the error ... if (urls.length > 0) runNextAjax(); else displayAllData(); } }); }; // Start the sequence off. runNextAjax();