栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在一系列异步XHR调用之后添加“回调”的最佳方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在一系列异步XHR调用之后添加“回调”的最佳方法

更好的答案

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});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/401664.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号