jQuery版AJAX简易封装_ajax封装的jquery函数
2017-12-21 14:41:13 By: shinyuu
开发过程中,AJAX的应用应该说非常频繁,当然,jQuery的AJAX函数已经非常好用,但是小编还是稍微整理下,方便不同需求下,可以简化输入参数,下面是实例代码:
$(function(){ /** * ajax封装 * url 发送请求的地址 * data 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1} * async 默认值: true。默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。 * 注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。 * type 请求方式("POST" 或 "GET"), 默认为 "GET" * dataType 预期服务器返回的数据类型,常用的如:xml、html、json、text * successfn 成功回调函数 * errorfn 失败回调函数 */ jQuery.syncAjax=function(url, data, async, type, dataType, successfn, errorfn) { async = (async==null || async=="" || typeof(async)=="undefined")? "true" : async; type = (type==null || type=="" || typeof(type)=="undefined")? "post" : type; dataType = (dataType==null || dataType=="" || typeof(dataType)=="undefined")? "json" : dataType; data = (data==null || data=="" || typeof(data)=="undefined")? {"date": new Date().getTime()} : data; $.ajax({ type: type, async: async, data: data, url: url, dataType: dataType, success: function(d){ successfn(d); }, error: function(e){ errorfn(e); } }); }; /** * ajax封装 * url 发送请求的地址 * data 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1} * successfn 成功回调函数 */ jQuery.jsonAjax=function(url, data, successfn) { data = (data==null || data=="" || typeof(data)=="undefined")? {"date": new Date().getTime()} : data; $.ajax({ type: "post", data: data, url: url, dataType: "json", success: function(d){ successfn(d); } }); }; /** * ajax封装 * url 发送请求的地址 * data 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1} * dataType 预期服务器返回的数据类型,常用的如:xml、html、json、text * successfn 成功回调函数 * errorfn 失败回调函数 */ jQuery.jsonAjax2=function(url, data, successfn, errorfn) { data = (data==null || data=="" || typeof(data)=="undefined")? {"date": new Date().getTime()} : data; $.ajax({ type: "post", data: data, url: url, dataType: "json", success: function(d){ successfn(d); }, error: function(e){ errorfn(e); } }); }; });
若资源对你有帮助,浏览后有很大收获,不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力。
想获取DD博客最新代码,你可以扫描下方的二维码,关注DD博客微信公众号(ddblogs)。
或者你也可以关注我的新浪微博,了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)
如对资源有任何疑问或觉得仍然有很大的改善空间,可以对该博文进行评论,希望不吝赐教。
为保证及时回复,可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)
感谢你的访问,祝你生活愉快、工作顺心、欢迎常来逛逛。
845224315@qq.com 2018-01-17 10:34:42 1 评 | 回复
2018网赚新项目,抢先机--我的座右铭:做不到日赚万元,死不瞑目!一辈子只做好一件事! 1.2018年最有潜力的赚钱项目,目前红利期不要错过。 2.稳定,每天赚个500-1000左右,我已经持续了一个多月,不然我也教不了你。 3.正规项目,可以长期操作。真正想赚钱的我可以教你,你赚了钱再来拜师。 4.好项目经得起考验,绝对不是垃圾项目,说的再好,你不做也是枉然。 5.虽然我不是大师,但是我能带你月赚万元绝没问题,直接复制我的就OK,不懂手把手教。 做网赚,别想一步登天,不是每个人都能赚钱的。如果,你没有坚定的信念,还是老老实实去上 班吧! 想清楚了再加我的微信,我要的是你勇往向前的决心,微信sgvg6666 (写验证码126,加我必通过) 我的座右铭:做不到日赚万元,死不瞑目!一辈子只做好一件事!