您的当前位置:首页>全部文章>文章详情

jQuery.ajax对应的post/get/delete/put请求方法封装

发表于:2021-12-08 15:02:57浏览:1041次TAG: #前端 #jquery #封装

jQuery ajax中的post/get/delete/put请求方法的写法过于繁琐,所以现在封装成如下简便的形式:


1、获取数据ajax-get请求

 /**
     * 获取数据ajax-get请求
     */
    $.getJSON = function (url,data,callback){
        $.ajax({
            url:url,
            type:"get",
            contentType:"application/json",
            dataType:"json",
            timeout:10000,
            data:data,
            success:function(data){
                callback(data);
            }
        });
    };


2、提交json数据的post请求

   /**
     * 提交json数据的post请求
     */
    $.postJSON = function(url,data,callback){
        $.ajax({
            url:url,
            type:"post",
            contentType:"application/json",
            dataType:"json",
            data:data,
            timeout:60000,
            success:function(msg){
                callback(msg);
            },
            error:function(xhr,textstatus,thrown){

            }
        });
    };

3、修改数据的ajax-put请求

    /**
     * 修改数据的ajax-put请求
     */
    $.putJSON = function(url,data,callback){
        $.ajax({
            url:url,
            type:"put",
            contentType:"application/json",
            dataType:"json",
            data:data,
            timeout:20000,
            success:function(msg){
                callback(msg);
            },
            error:function(xhr,textstatus,thrown){

            }
        });
    };

4、删除数据的ajax-delete请求

    /**
     * 删除数据的ajax-delete请求
     */
    $.deleteJSON = function(url,data,callback){
        $.ajax({
            url:url,
            type:"delete",
            contentType:"application/json",
            dataType:"json",
            data:data,
            success:function(msg){
                callback(msg);
            },
            error:function(xhr,textstatus,thrown){

            }
        });
    };