更好的答案 :
function saveRecords(callback, errorCallback){ $('<div></div>').ajaxStop(function(){ $(this).remove(); // Keep future AJAX events from effecting this callback(); }).ajaxError(function(e, xhr, options, err){ errorCallback(e, xhr, options, err); }); $(search).each(function() { $.get('save.x3', { id: $(this).attr("id"), value: $(this).data("value") }); });}可以这样使用:
saveRecords(function(){ // Complete will fire after all requests have completed with a success or error}, function(e, xhr, options, err){ // Error will fire for every error});原始答案 :如果它们需要按一定顺序排列,或者页面上有其他常规AJAX事件会影响的使用
ajaxStop,则这样做会很好,但这会比较慢:
function saveRecords(callback){ var recs = $(search).map(function(i, obj) { return { id: $(obj).attr("id"), value: $(obj).data("value") }; }); var save = function(){ if(!recs.length) return callback(); $.ajax({ url: 'save.x3', data: recs.shift(), // shift removes/returns the first item in an array success: function(o){ save(); }, error: function(o){ //Update progress callback(o.status); } }); } save();}然后您可以这样称呼它:
saveRecords(function(error){ // This function will run on error or after all // commands have run});


