码迷,mamicode.com
首页 > Web开发 > 详细

jquery Ajax 全局调用封装

时间:2016-06-03 10:12:24      阅读:507      评论:0      收藏:0      [点我收藏+]

标签:


有一种情况:全站都要用异步方式来调用 数据,提交数据,那么你每次操作 都会要$.ajax({.....})


写重复的方法 和代码,冗余太大, 也浪费时间,虽说你有代码自动提示补全,但真的不优雅,身为前端极客,是不能允许的!

【嘿嘿!虽说我现在基本不用jquery了 ,不过异步概念 是永远要用的,就帮助下新人】

jQuery Ajax通用js封装

第一步:引入jQuery库

<script type="text/javascript" src="/js/jquery.min.js"></script>

第二步:开发Ajax封装类,已测试通过,可以直接调用,直接贴代码,讲解就省了

技术分享
/*****************************************************************
                  jQuery Ajax封装通用类  (linjq)       
*****************************************************************/
$(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.ax=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.axpost=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.axspost=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);
            }
        });
    };



});
技术分享

第三步:调用模拟

技术分享
<!DOCTYPE html>
<html>
    <head>
        <base href="<%=basePath%>">

        <title>jQuery Ajax封装通用类测试</title>

        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <jsp:include page="/view/common/js_taglib.jsp"></jsp:include>
        <script type="text/javascript">
        $(function(){
            $.ax(
                getRootPath()+"/test/ajax.html",
                null,
                null,
                null,
                null, 
                function(data){
                    alert(data.code);
                }, 
                function(){
                    alert("出错了");
                }
            );
            
            $.axpost(getRootPath()+"/test/ajax.html", null, function(data){
                alert(data.data);
            });
        
            $.axspost(getRootPath()+"/test/ajax.html",
                null, 
                function(){
                    alert("成功了");
                },
                function(){
                    alert("出错了");
            });
        });
          </script>
    </head>
    <body>
         
    </body>
</html>
技术分享

 

$.axpost(getRootPath()+"/test/ajax.html", null, function(data){
                alert(data.data);
            });

如上代码:只要填写 url,和要传输的 data 字段就行了,避免了重复工作和代码冗余。

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

如转载,敬请注明地址。

JS前端实用开发QQ群 :147250970  欢迎加入~!


Gulp前端自动化教程: 你还停留在刀耕火种的年代,还是接受洗礼进入前端工业化时代?如果你对web前端有浓烈兴趣和爱好,如果你想摆脱手动整理代码结构的烦恼,如果你不再想手动刷新页面,如果你想在后端面前也装一下,那么我们一起嗨皮,快来进入gulp完全自动化的世界吧!

去报名:免费技术公开课 Gulp 自动化  CSDN直播,学新技术的快来

去报名:【免费技术公开课】Gulp 前端自动化之:Gulp安装及文件配置- 如何多屏自动刷新页面
http://edu.csdn.net/huiyiCourse/detail/130 --点此报名
完全免费、直播。感兴趣的 学新技术的快来!
开课时间 :2016年6月8号 晚 8点到9点



jquery Ajax 全局调用封装

标签:

原文地址:http://blog.csdn.net/xllily_11/article/details/51567186

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!