• Ajax的封装。


    封装 Ajax

    因为Ajax 使用起来比较麻烦,主要就是参数问题,比如到底使用GET 还是POST;到

    底是使用同步还是异步等等,我们需要封装一个Ajax 函数,来方便我们调用。

       封装支持接收来自服务端的数据,不可以发送数据到服务端

    /**
    
    * 此封装只支持接收来自服务端的数据,不可以发送数据到服务端
    
     */
    
    function ajax(obj) {
    
        var xhr = new XMLHttpRequest();
    
        obj.url = obj.url + '?rand=' + Math.random();
    
        xhr.open(obj.method, obj.url, obj.async);
    
        xhr.send(null);
    
        if (obj.async === false) {
    
            callback();
    
        }
    
        if (obj.async === true) {
    
            xhr.onreadystatechange = function () {
    
                if (xhr.readyState == 4) {
    
                    callback();
    
                }
    
            };
    
        }
    
        function callback () {
    
            if (xhr.status == 200) {
    
                obj.success(xhr.responseText); //回调
    
            } else {
    
                alert('数据返回失败!状态代码:' + xhr.status + ',状态信息:' + xhr.statusText);
    
            }
    
        }
    
    }
    

      

       把上面的代码封装在ajax2.js中,在页面上引入该文件。

    <!DOCTYPE html>
    
    <html>
    
    <head>
    
        <title>Ajax的封装</title>
    
        <meta charset="utf-8">
    
        <script src="ajax2.js"></script>
    
    </head>
    
    <body>
    
    <button id="btn">调用Ajax</button>
    
    <script>
    
        document.getElementById("btn").onclick=function(){
    
            ajax({
    
                method : 'get',
    
                url : 'http://localhost:3000/api/2',
    
                success : function (text) {
    
                    alert(text);
    
                },
    
                async :false
    
            });
    
        };
    
    </script>
    
    </body>
    
    </html>
    
    7.2  封装支持接收来自服务端的数据,又可以发送数据到服务端
    
    function ajax(obj) {
    
        var xhr = new XMLHttpRequest();
    
        obj.url = obj.url + '?rand=' + Math.random();
    
        obj.data = params(obj.data);
    
        if (obj.method === 'get') {
    
            obj.url = obj.url.indexOf('?') == -1 ? obj.url + '?' + obj.data : obj.url + '&' + obj.data;
    
        }
    
     
    
        if (obj.async === true) {
    
            xhr.onreadystatechange = function () {
    
                if (xhr.readyState == 4) {
    
                    callback();
    
                }
    
            };
    
        }
    
        xhr.open(obj.method, obj.url, obj.async);
    
        if (obj.method === 'post') {
    
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    
            xhr.send(obj.data);
    
        } else {
    
            xhr.send(null);
    
        }
    
        if (obj.async === false) {
    
            callback();
    
        }
    
        function callback () {
    
            if (xhr.status == 200) {
    
                obj.success(xhr.responseText); //回调
    
            } else {
    
                alert('数据返回失败!状态代码:' + xhr.status + ',状态信息:' + xhr.statusText);
    
            }
    
        }
    
    }
    
     
    
    //名值对编码
    
    function params(data) {
    
        var arr = [];
    
        for (var i in data) {
    
            arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
    
        }
    
        return arr.join('&');
    
    }
    

              希望能够帮到你!

  • 相关阅读:
    java中浮点数的比较(double, float)(转)
    SVN与TortoiseSVN实战:补丁详解(转)
    常见名词解析
    SSL连接建立过程分析(1)
    Flash-使用变形面板制作花朵
    使用ReactiveCocoa实现iOS平台响应式编程
    【LaTeX排版】LaTeX论文排版&lt;三&gt;
    angularjs入门学习【指令篇】
    理解class.forName()
    malloc()与calloc差别
  • 原文地址:https://www.cnblogs.com/nujufoul/p/7050382.html
Copyright © 2020-2023  润新知