数智学习中心 计科随机库
学习专区 Linux专栏 博客圈 计科之路 登录
简单封装JavaScript的AJAX请求

一、目的

用一些全局对象、匿名函数、回调函数来简单的封装XMLHttpRequest对象的请求。

二、主要代码

(一)封装的类

主要存放在httpapi.js文件中。

内容如下:

// 定义类HttpApi
function HttpApi(){

    // 定义公共的请求函数
    // 参数:
    //   method:是方法,例如 GET、POST
    //   url:是HTTP路径。
    //   headers:是存放请求头部的JSON对象,例如 {"Content-Type":"application/json"}
    //   body:是请求体对象,可以是字符串、FormData对象两种。
    //   ok_call:是请求成功时会执行的回调函数。
    //   error_call:是请求发生错误时执行的回调函数。
    this.request = function(method, url, headers, body, ok_call, error_call){
        var xhr = new XMLHttpRequest();
        xhr.open(method, url, true);

        if(headers != null){
            // 遍历对象,设置请求头
            for(key in headers){
                xhr.setRequestHeader(key, headers[key]);
            }
        }
        xhr.onload = function(){
            // 回调函数的三个参数:HTTP状态码、响应体字符串、XMLHttpRequest对象
            ok_call(xhr.status, xhr.responseText, xhr);
        };

        xhr.onerror = function(){
            // 回调函数的参数:XMLHttpRequest对象
            error_call(xhr);
        };

        // 如果请求体不为空
        if(body != null){
            xhr.send(body);
        } else {
            xhr.send();
        }

    };

    // 发起GET请求
    this.get = function(url, headers, ok_call, error_call){
        this.request("GET", url, headers, null, ok_call, error_call);
    };

    // 发起POST请求
    this.post = function(url, headers, body, ok_call, error_call){
        this.request("POST", url, headers, body, ok_call, error_call);
    };

    // 发起PUT请求
    this.put = function(url, headers, body, ok_call, error_call){
        this.request("PUT", url, headers, body, ok_call, error_call);
    };

    // 发起DELETE请求
    this.delete = function(url, headers, body, ok_call, error_call){
        this.request("DELETE", url, headers, body, ok_call, error_call);
    };
}



// 创建全局对象
var http = new HttpApi();

(二)测试代码

<html>
    <head>
        <title>测试AJAX封装库</title>
    </head>
    <body>
       <textarea id="t" rows="15" cols="20"></textarea>

       <button type="button" onclick="do_get()">执行请求</button>

       <!-- 引入自定义的httpapi.js文件   -->
       <script src="./httpapi.js"></script>

       <script>
           // 用id属性获得<textarea>标签对象
           var tdom = document.getElementById("t");

           // 定义发起GET请求的函数
           function do_get(){
               // 使用案例
               // 用全局对象http,调用get()函数
               // 依次传入HTTP路径、请求头部、成功回调函数、失败回调函数
               http.get("http://localhost/index.html", {},
                   function(status, data, xhr){
                       tdom.value = "";

                       // 把返回响应体的字符串显示在<textarea>标签中
                       tdom.value = data;
                       console.log("状态码:" + status);
                   },function(xhr){
                       alert("请求出错!");
                   }
               );
           }
       </script>


    </body>
</html>

评论留言

一共0条留言