jQuery+AJAX请求的统一封装

记录一下使用jQuery+AJAX对http请求的统一封装

很久都没有使用jquery和ajax的组合了,这里记录一下jquery和ajax的组合简单封装 将来或许有机会重新启用这个组合

新建jquery.request.js;demo目录结构如下
myw


const baseURL = 'http://127.0.0.1:8116';

//  const baseURL = "";

const timeout = 3000;

// requet ajax
function request (url, method, data = {}, contentType, back){
    $.ajax({
        url: baseURL+url,
        type: method,
        data: data,
        cache: false,
        timeout: timeout,
        contentType: contentType,
        dataType: "json",
        success: function(res){
            console.log(res)
            return typeof back == "function" && back(res);
        },
        error: function(error) {
            console.log(error)
            return typeof back == "function" && back(null);
        }
    });   
};
function getAjaxRequst (url, data, callBack) {
    request(url, "GET", data, "application/x-www-form-urlencoded;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};
function postAjaxRequst (url, data, callBack) {
    request(url, "POST", data, "application/x-www-form-urlencoded;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};

index.html里jquery的引用必须放在request的前面

    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="jquery.request.js"></script>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="jquery.request.js"></script>
    <title>jquery.request-demo</title>
    <style></style>
</head>

<body>

<div class="">

</div>
<script type="text/javascript">

    $(function() {
        requestGetLoginDemo();
        requestPostLoginDemo();
    });

    function requestGetLoginDemo() {
        var data = { username: "myyhtw", password: "123456"}
        getAjaxRequst('/auth/login', data, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }

    function requestPostLoginDemo() {
        var data = { username: "myyhtw", password: "123456"}
        postAjaxRequst('/auth/login', data, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }

    
</script>

</body>

</html>

后端使用SpringBoot写了get和post请求登录的2个接口示例
myw
myw
这里使用的是application/x-www-form-urlencoded;charset=UTF-8,一般我们使用的都是json数据,于是呢可以改变下jquery.request.js

application/json;charset=UTF-8

// requet ajax json token
function httpJsonRequest (url, method, data = {}, token, contentType, back){
    $.ajax({
        url: baseURL+url,
        type: method,
        data: JSON.stringify(data),
        cache: false,
        timeout: timeout,
        headers: {'token': token},
        contentType: contentType,
        dataType: "json",
        success: function(res){
            console.log(res)
            return typeof back == "function" && back(res);
        },
        error: function(error) {
            console.log(error)
            return typeof back == "function" && back(null);
        }
    });   
};
function getAjaxJsonHttpRequst (url, data, token, callBack) {
    httpJsonRequest(url, "GET", data, token, "application/json;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};
function postAjaxJsonHttpRequst (url, data, token, callBack) {
    httpJsonRequest(url, "POST", data, token, "application/json;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};

index.html

$(function() {
    requestJsonGetLoginDemo();
    requestJsonPostLoginDemo();
});

function requestJsonGetLoginDemo() {
    var username = "myyhtw"; 
    var password = "123456";
    getAjaxJsonHttpRequst('/auth/login/'+username+"/"+password, null, null, function(res) {
        console.log(res)
        if(res){
            console.log("需要的数据")
        } else {
            console.log("返回数据不存在或者请求数据失败")
        }
    })
}

function requestJsonPostLoginDemo() {
    var data = { username: "myyhtw", password: "123456"}
    postAjaxJsonHttpRequst('/auth/login', data, null, function(res) {
        console.log(res)
        if(res){
            console.log("需要的数据")
        } else {
            console.log("返回数据不存在或者请求数据失败")
        }
    })
}

后端使用SpringBoot写了get和post请求json格式登录的2个接口示例

myw
myw

完整jquery.request.js



const baseURL = 'http://127.0.0.1:8116';

//  const baseURL = "";

const timeout = 3000;

// requet ajax
function request (url, method, data = {}, contentType, back){
    $.ajax({
        url: baseURL+url,
        type: method,
        data: data,
        cache: false,
        timeout: timeout,
        contentType: contentType,
        dataType: "json",
        success: function(res){
            console.log(res)
            return typeof back == "function" && back(res);
        },
        error: function(error) {
            console.log(error)
            return typeof back == "function" && back(null);
        }
    });   
};
function getAjaxRequst (url, data, callBack) {
    request(url, "GET", data, "application/x-www-form-urlencoded;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};
function postAjaxRequst (url, data, callBack) {
    request(url, "POST", data, "application/x-www-form-urlencoded;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};


// requet ajax json token
function httpJsonRequest (url, method, data = {}, token, contentType, back){
    $.ajax({
        url: baseURL+url,
        type: method,
        data: JSON.stringify(data),
        cache: false,
        timeout: timeout,
        headers: {'token': token},
        contentType: contentType,
        dataType: "json",
        success: function(res){
            console.log(res)
            return typeof back == "function" && back(res);
        },
        error: function(error) {
            console.log(error)
            return typeof back == "function" && back(null);
        }
    });   
};
function getAjaxJsonHttpRequst (url, data, token, callBack) {
    httpJsonRequest(url, "GET", data, token, "application/json;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};
function postAjaxJsonHttpRequst (url, data, token, callBack) {
    httpJsonRequest(url, "POST", data, token, "application/json;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};




index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="jquery.request.js"></script>
    <title>jquery.request-demo</title>
    <style></style>
</head>

<body>

<div class="">

</div>
<script type="text/javascript">

    $(function() {
        // requestGetLoginDemo();
        // requestPostLoginDemo();
        requestJsonGetLoginDemo();
        requestJsonPostLoginDemo();
    });

    function requestJsonGetLoginDemo() {
        var username = "myyhtw"; 
        var password = "123456";
        getAjaxJsonHttpRequst('/auth/login/'+username+"/"+password, null, null, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }

    function requestJsonPostLoginDemo() {
        var data = { username: "myyhtw", password: "123456"}
        postAjaxJsonHttpRequst('/auth/login', data, null, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }


    function requestGetLoginDemo() {
        var data = { username: "myyhtw", password: "123456"}
        getAjaxRequst('/auth/login', data, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }

    function requestPostLoginDemo() {
        var data = { username: "myyhtw", password: "123456"}
        postAjaxRequst('/auth/login', data, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }

    
</script>

</body>

</html>
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
jQueryajax封装主要分为三个步骤。首先,需要引入jQuery库。然后,通过代码实例来讲解。最后,根据代码注释来理解封装过程。 具体来说,封装的步骤如下: 1. 第一步:引入jQuery库。用户需要在页面中引入jQuery的库文件,可以通过以下方式引入: ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> ``` 这样就可以在页面中使用jQuery的功能了。 2. 第二步:使用jQueryajax方法进行封装。用户可以通过以下代码将ajax请求进行封装: ``` $('#id').click(function(){ $.ajax({ url: "http://localhost:3000/ind", type: "post/get", data: $('form').serialize(), dataType: 'json', success: function(result){ // 请求成功后的回调函数,result中存放的是服务器的响应数据 }, error: function(err){ console.log(err); } }); }); ``` 在这段代码中,通过给一个元素绑定点击事件,当该元素被点击时,发起ajax请求。可以根据实际需求,修改url、type、data等参数来满足不同的请求。 3. 第三步:高层封装。除了使用jQueryajax方法,还可以使用高层封装的post请求实现简洁的代码,代码如下: ``` $.post(url, [data], [callback], [type]); ``` 其中,url是请求的地址,data是待发送的参数,callback是请求成功后的回调函数,type是返回内容的格式。 综上所述,jQueryajax封装通过引入jQuery库、使用ajax方法进行封装以及高层封装来实现。这样可以简化代码,提高开发效率。同时,原生的Ajax也是一种封装方式,可以使用XMLHttpRequest对象来发送异步请求,通过open方法建立与服务器的连接,设置请求头信息,然后通过send方法向服务器发送请求,并通过onreadystatechange事件监听请求-响应状态的改变,并将响应信息写入页面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值