ajax封装

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax封装</title>
</head>

<body>
    <input type="button" value="按钮1" id="btn1">
    <input type="button" value="按钮2" id="btn2">
    <input type="button" value="按钮3" id="btn3">
</body>
<script>

    var ajax = {
        getxhr: function () {
            return new XMLHttpRequest();
        },
        get: function (url, sync = true,fun) {
            
            var xhr = this.getxhr();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    fun(xhr.responseText);
                }
            }
            xhr.open('get', url, sync);
            xhr.send();
        },
        post: function (url, post_data, sync = true,fun) {
            var xhr = this.getxhr();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    fun(xhr.responseText);
                }
            }
            xhr.open('post', url, sync);
            xhr.send(post_data);
        }
    }


    document.getElementById('btn1').onclick = function(){
        
        ajax.get('http://127.0.0.1:8080/gets',true,function(data){
            alert(data);
        });

        ajax.post('http://127.0.0.1:8080','name=lisi',true,function(data){
            alert(data);
        })
    }

</script>

</html>
(function () {

    var ajax = {
        getxhr: function () {
            return new XMLHttpRequest();
        },
        get: function (url, fun, sync = true) {
            // 调用对象中的方法获取xhr对象
            var xhr = this.getxhr();
            // 设置状态码改变事件
            xhr.onreadystatechange = function () {
                // 状态码为4 说明服务器返回结束 客户端接收到全部数据
                if (xhr.readyState == 4) {

                    fun(xhr.responseText);
                }
            }
            xhr.open('get', url, sync);
            xhr.send();
        },

        post: function (url, post_data, sync = true, fun) {
            var xhr = this.getxhr();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    fun(xhr.responseText);
                }
            }
            xhr.open('post', url, sync);
            xhr.send(post_data);
        }
    }

    // 封装时将封装内容给window对象
    // 不要和现有window对象中的属性重名
    window.myajax = ajax;

})()

 

posted @ 2021-03-13 19:57  华北业余选手  阅读(28)  评论(0)    收藏  举报