• js原生Ajax的封装与使用


    一、原生Ajax代码的封装如下:

    (function() {
    
        var XHR = {
            createStandardXHR: function() {
                return new XMLHttpRequest();
            },
            createIEXHR: function () {
                return new ActiveXObject("Microsoft.XMLHTTP");
            },
            createErrorXHR: function () {
                alert("Your browser does not support XMLHTTP.");
                return null;
            },
            createXHR: function() { //创建XMLHttpRequest对象
                var xhr = null;
                if (window.XMLHttpRequest) {
                    this.createXHR = this.createStandardXHR; // Firefox, Opera 8.0+,Safari,IE7+
                } else {
                    this.createXHR = this.createIEXHR; // IE5、IE6
                }
                try {
                    xhr = this.createXHR();
                } catch (e) {
                    this.createXHR = this.createErrorXHR;
                    xhr = this.createXHR();
                }
                return xhr;
            },
            ajax: function(opts) {
                var xhr = this.createXHR(),
                    ajaxMethod = (opts.type || "GET").toUpperCase(),
                    isPost = ajaxMethod == "POST",
                    data = this.param(opts.data),
                    url = this.buildUrlParam(opts.url, data, isPost);
                xhr.open(ajaxMethod, url, opts.async == undefined ? true : opts.async);
                if (isPost) {
                    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                }
                if (opts.contentType) {
                    xhr.setRequestHeader("Content-type", opts.contentType);
                }
                var stateChange = this.xhrStateChange;
                xhr.onreadystatechange = function() {
                    stateChange(xhr, opts.success, opts.error);
                }
                xhr.send(isPost ? data : null);
            },
            buildUrlParam: function(url,data,isPost) {
                if (data && !isPost) {
                    if (url.indexOf("?") < 0) {
                        url += "?" + data;
                    } else {
                        url += "&" + data;
                    }
                }
                return url;
            },
            param: function(data) {
                if (!data) {
                    return null;
                }
    
                if (typeof data !== "object") {
                    return data;
                }
                var postData = [];
                for (var key in data) {
                    postData.push(key+"="+data[key]);
                }
    
                return postData.join("&");
            },
            xhrStateChange: function(xhr, successFn, failFn) {
                if (xhr.readyState == 4) { // 4 = "loaded"
                    if (xhr.status == 200) { // 200 = OK
                        successFn(xhr.responseText);
                    } else {
                        failFn.call(xhr, xhr.statusText, xhr.status);
                    }
                } else {
                    failFn.call(xhr, xhr.statusText, xhr.status);
                }
            }
        };
    
        window.ajax = function(opts) {
            XHR.ajax.call(XHR, opts);
        };
    })();
    

    二、方法如下:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="gb2312" />
        <title>ajax demo02 </title>
        <style type="text/css">
            .msg {
                height: 30px;
                color: #ff6347;
                margin-top: 10px;
            }
        </style>
    </head>
    <body>
        <div>员工编号:<input type="text" id="txtNumber" /><input id="btnSearch" type="button" value="查询" /></div>
        <div id="searchResult" class="msg"></div>
        <div style="margin-top: 100px;">员工姓名:<input type="text" id="txtName" /><input id="btnSave" type="button" value="保存" /></div>
        <div id="saveResult" class="msg"></div>
        <script src="ajax.js"></script>
        <script type="text/javascript">
            getDom("btnSearch").onclick = function () {
                ajax({
                    url: "ajax_server/service.aspx?action=search",
                    data: {
                        number: encodeURIComponent(getDom("txtNumber").value)
                    },
                    success: function (data) {
                        getDom("searchResult").innerHTML = data;
                    },
                    error: function (message, code) {
                        getDom("searchResult").innerHTML = "出错," + message;
                    }
                });
            }
    
            getDom("btnSave").onclick = function () {
                ajax({
                    url: "ajax_server/service.aspx?action=save",
                    type: "post",
                    data: { Name: encodeURIComponent(getDom("txtName").value) },
                    success: function (data) {
                        getDom("saveResult").innerHTML = data;
                    },
                    error: function (message, code) {
    
                    }
                });
            }
    
            function getDom(id) {
                return document.getElementById(id);
            }
        </script>
    </body>
    </html>
    

    三、代码及Demo下载

  • 相关阅读:
    linux系统——机制与策略(三)
    linux系统——机制与策略(二)
    Linux系统——机制策略(一)
    RTSP会话基本流程
    linux编程学习
    编码风格——linux内核开发的coding style
    编程风格——整洁代码的4个提示
    编程风格——五种应该避免的代码注释
    十条不错的编程观点
    代码优化概要
  • 原文地址:https://www.cnblogs.com/junjieok/p/4538580.html
Copyright © 2020-2023  润新知