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

如何使用jQuery链接ajax调用

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

如何使用jQuery链接ajax调用

带有自定义对象

function DeferredAjax(opts) {    this.options=opts;    this.deferred=$.Deferred();    this.country=opts.country;}DeferredAjax.prototype.invoke=function() {    var self=this, data={country:self.country};    console.log("Making request for [" + self.country + "]");    return $.ajax({        type: "GET",        url: "wait.php",        data: data,        dataType: "JSON",        success: function(){ console.log("Successful request for [" + self.country + "]"); self.deferred.resolve();        }    });};DeferredAjax.prototype.promise=function() {    return this.deferred.promise();};var countries = ["US", "CA", "MX"], startingpoint = $.Deferred();startingpoint.resolve();$.each(countries, function(ix, country) {    var da = new DeferredAjax({        country: country    });    $.when(startingpoint ).then(function() {        da.invoke();    });    startingpoint= da;});

小提琴http://jsfiddle.net/7kuX9/1/

为了更清楚一点,可以写最后几行

c1=new DeferredAjax( {country:"US"} );c2=new DeferredAjax( {country:"CA"} );c3=new DeferredAjax( {country:"MX"} );$.when( c1 ).then( function() {c2.invoke();} );$.when( c2 ).then( function() {c3.invoke();} );

带管道

function fireRequest(country) {        return $.ajax({ type: "GET", url: "wait.php", data: {country:country}, dataType: "JSON", success: function(){     console.log("Successful request for [" + country + "]"); }        });}var countries=["US","CA","MX"], startingpoint=$.Deferred();startingpoint.resolve();$.each(countries,function(ix,country) {    startingpoint=startingpoint.pipe( function() {        console.log("Making request for [" + country + "]");        return fireRequest(country);    });});

http://jsfiddle.net/k8aUj/1/

编辑:在结果窗口中输出日志的小提琴http://jsfiddle.net/k8aUj/3/

每个管道调用都返回一个新的Promise,该诺言又用于下一个管道。请注意,我仅提供了sccess功能,应该为失败提供类似的功能。

在每种解决方案中,通过将Ajax调用包装到一个函数中来延迟它们,直到需要使用为止,并为列表中的每个项目创建一个新的Promise以构建链。

我相信自定义对象提供了一种操作链的简便方法,但是管道可以更好地适合您的口味。

注意 :从jQuery
1.8开始,

deferred.pipe()
不推荐使用,
deferred.then
将其替换。



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

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

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