模仿jquery封装ajax功能

更新日期: 2019-08-10阅读: 2.3k标签: ajax

需求分析

因为有时候想提高性能,只需要一个ajax函数,不想引入较大的jq文件,尝试过axios,可是get方法不支持多层嵌套的json,post方式后台接收方式似乎要变。。也许是我不太会用吧。。其实换个方式接收也没什么,只是习惯了JQ序列化参数。所以上网搜集了很多资料,同时也进一步了解了一点JQ。以下代码很多来自于网上,自己整合了一下。

 

封装代码

var Ajax = {};
(function($) {

    function ajax(options) {
        var str;
        var xmlHttpRequest;
        var timer;
        if (window.XMLHttpRequest) {
            xmlHttpRequest = new XMLHttpRequest();
        } else {
            xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        options = Object.assign({}, { type: "GET", processData: true, contentType: "application/x-www-form-urlencoded" }, options);
        if (options.type.toUpperCase() !== "GET") {
            xmlHttpRequest.open(options.type.toUpperCase(), options.url, true);
            xmlHttpRequest.setRequestHeader("Content-type", options.contentType);
            if (options.processData) {
                str = param(options.data);
            } else {
                str = options.data;
            }
            xmlHttpRequest.send(str);
        } else {
            str = param(Object.assign(urlorQuerytoObject(options.url), options.data));
            if (options.url.indexOf("?") !== -1) {
                options.url = options.url.substr(0, options.url.indexOf("?"));
            }
            xmlHttpRequest.open("GET", options.url + "?" + str, true);
            xmlHttpRequest.send(null);
        }
        xmlHttpRequest.onreadystatechange = function() {
            if (xmlHttpRequest.readyState === 4) {
                clearInterval(timer);
                if (xmlHttpRequest.status === 200) {
                    try {
                        // 如果是JSON格式,自动转换为JSON对象
                        options.success(JSON.parse(xmlHttpRequest.responseText));
                    } catch (e) {
                        options.success(xmlHttpRequest.responseText);
                    }
                } else if (options.error) {
                    if (xmlHttpRequest.status === 304) {
                        options.error(xmlHttpRequest, "notmodified");
                    } else {
                        options.error(xmlHttpRequest, xmlHttpRequest.statusText);
                    }
                }
            }
        };
        //判断是否超时
        if (options.timeout) {
            timer = setTimeout(function() {
                if (options.error) {
                    options.error(xmlHttpRequest, "timeout");
                }
                xmlHttpRequest.abort();
            }, options.timeout);
        }
    }

    // 把url中的查询字符串转为对象,主要是想当方式为get时,用data对象的参数覆盖掉url中的参数
    function urlorQuerytoObject(urlorQuery) {
        var queryArr = [];
        var urlSplit = urlorQuery.split("?");
        queryArr[0] = urlSplit[0];
        if (urlSplit[1]) {
            queryArr[0] = urlSplit[1];
        }
        queryArr = queryArr[0].split("&");
        var obj = {};
        var i = 0;
        var temp;
        var key;
        var value;
        for (i = 0; i < queryArr.length; i += 1) {
            temp = queryArr[i].split("=");
            key = temp[0];
            value = temp[1];
            obj[key] = value;
        }
        return obj;
    }

    // 序列化参数
    // 转载自 https://www.jianshu.com/p/0ca22d53feea
    function param(obj, traditional) {

        if (traditional === "undefined") { traditional = false; }
        var
            rbracket = /\[\]$/,
            op = Object.prototype,
            ap = Array.prototype,
            aeach = ap.forEach,
            ostring = op.toString;

        function isFunction(it) {
            return ostring.call(it) === "[object Function]";
        }

        function isArray(it) {
            return ostring.call(it) === "[object Array]";
        }

        function isObject(it) {
            return ostring.call(it) === "[object Object]";
        }

        function buildParams(prefix, obj, traditional, add) {
            var name;
            if (isArray(obj)) {
                // Serialize array item.
                aeach.call(obj, function(v, i) {
                    if (traditional || rbracket.test(prefix)) {
                        // Treat each array item as a scalar.
                        add(prefix, v);
                    } else {
                        // Item is non-scalar (array or object), encode its numeric index.
                        buildParams(
                            prefix + "[" + (typeof v === "object" && v != null ? i : "") + "]",
                            v,
                            traditional,
                            add
                        );
                    }
                });
            } else if (!traditional && isObject(obj)) {
                // Serialize object item.
                for (name in obj) {
                    buildParams(prefix + "[" + name + "]", obj[name], traditional, add);
                }
            } else {
                // Serialize scalar item.
                add(prefix, obj);
            }
        }
        // Serialize an array of form elements or a set of
        // key/values into a query string
        function jollyparam(a, traditional) {
            var prefix,
                s = [],
                add = function(key, valueOrFunction) {
                    // If value is a function, invoke it and use its return value
                    var value = isFunction(valueOrFunction) ? valueOrFunction() : valueOrFunction;
                    s[s.length] = encodeURIComponent(key) + "=" +
                        encodeURIComponent(value == null ? "" : value);
                };
            // If an array was passed in, assume that it is an array of form elements.
            if (isArray(a)) {
                // Serialize the form elements
                aeach.call(a, function(item) {
                    add(item.name, item.value);
                });
            } else {
                // If traditional, encode the "old" way (the way 1.3.2 or older
                // did it), otherwise encode params recursively.
                for (prefix in a) {
                    buildParams(prefix, a[prefix], traditional, add);
                }
            }
            // Return the resulting serialization
            return s.join("&");
        }
        return jollyparam(obj, traditional);
    }

    // 为避免 Object.assign 不能使用
    // 转载自 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
    if (typeof Object.assign != "function") {
        // Must be writable: true, enumerable: false, configurable: true
        Object.defineProperty(Object, "assign", {
            value: function assign(target, varArgs) { // .length of function is 2
                "use strict";
                if (target == null) { // TypeError if undefined or null
                    throw new TypeError("Cannot convert undefined or null to object");
                }
                var to = Object(target);
                for (var index = 1; index < arguments.length; index++) {
                    var nextSource = arguments[index];
                    if (nextSource != null) { // Skip over if undefined or null
                        for (var nextKey in nextSource) {
                            // Avoid bugs when hasOwnProperty is shadowed
                            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                                to[nextKey] = nextSource[nextKey];
                            }
                        }
                    }
                }
                return to;
            },
            writable: true,
            configurable: true
        });
    }

    $ = {
        get: function(url, data, success) {
            return ajax({ url: url, data: data, success: success });
        },
        post: function(url, data, success) {
            return ajax({ type: "POST", url: url, data: data, success: success });
        },
        ajax: function(options) { return ajax(options); },
        param: function(obj, traditional) { return param(obj, traditional); },
        urlorQuerytoObject: function(urlorQuery) { return urlorQuerytoObject(urlorQuery); }
    };

    // 满足 jquery 的使用习惯
    if (typeof window.$ === "undefined") {
        window.$ = $;
    }
})(Ajax);


用法

高度模仿JQ。

// get请求
$.get("", {}, function(data) {})

// post请求
$.post("", {}, function(data) {})

// 更完整的ajax
$.ajax({
    type: "post",
    // 非必须,默认 get
    url: "",
    data: {},
    // json格式
    processData: true,
    // 非必须,默认 true
    contentType: "application/json;charsetset=UTF-8",
    //非必须,默认 application/x-www-form-urlencoded
    success: function(data) {},
    timeout: 1000,
    // 超时时间,非必须,如果设置了,超时且存在error函数则会调用
    error: function(xhr, statusText) {// 非必须
    // statusText: "notmodified","timeout", 或者其他xmlHttpRequest.statusText
    }
});


注意事项

1. 如果 " $ " 符号不能使用,请用 " Ajax " 替代,这个变量名若仍有冲突,请修改源代码首尾两行。

2. 如果返回的是json格式的字符串,会自动将字符串转为json对象传给success函数参数,其他情况均为字符串。

来自:https://www.cnblogs.com/kill370354/archive/2019/09/10/11497480.html

链接: https://www.fly63.com/article/detial/5257

js中关于ajax笔试面试题汇总

什么是ajax?Ajax包含下列技术,为什么要用ajax?Ajax应用程序的优势在于?Ajax的最大的特点是什么?请介绍一下XMLHTTPREQUEST对象?Ajax技术体系的组成部分有哪些?AJAX应用和传统Web应用有什么不同...

Vue通过ajax获取数据,如何避免绑定的数据中出现 property of undefined错误

使用vue开发过程中,通过使用{{}}或者v-text=的形式进行数据绑定,如果数据是通过服务器异步获取的。在控制台我们会发现报这样的错误:Uncaught TypeError: Cannot read property name of null。通过v-if或者空对象来解决

js 判断异步执行完成方法总汇,比如多个ajax执行完毕后执行其他方法

在多个异步操作中,由于不确定异步操作的执行顺序,如何判断异步操作在已经执行完成的情况下,再执行一个新的操作,有哪些方法可以实现?

使用AJAX实现文件拖拽上传功能详解

前端选择文件上传的两种方式:对话框选择方式上传、拖拽选择方式上传;如何上传获取到的文件?使用AJAX即可通过表单方式上传文件。

ajax请求 get与post的区别?_get和post的使用场景

使用Ajax时,采用Get或者Post方式请求服务器,那么它们的区别有哪些呢?相比post,get请求参数跟在url后面,提交数据的长度长度有限制,而且会被浏览器缓存起来,存在一定的安全问题。

IE浏览器关于ajax的缓存机制

IE浏览器对于同一个URL只返回相同结果。因为,在默认情况下,IE会缓存ajax的请求结果。对于同一个URL地址,在缓存过期之前,只有第一次请求会真正发送到服务端。大多数情况下,我们使用ajax是希望实现局部刷新的

使用Ajax同步请求时,等待时间过长增加页面提示问题

后台的处理时间比较长,根据合同的多少可能等待时间比较长,会达到10s左右,这个时候如果不加任何的提示,会导致用户因为没有看到是否执行而导致重复的操作,为了增加用户的体验感,以及项目的完善性,这个时候就需要增加一个等待页面进行提示。

解决ajax跨域访问sessionid不一致问题

根据浏览器的保护规则,跨域的时候我们创建的sessionId是不会被浏览器保存下来的,这样,当我们在进行跨域访问的时候,我们的sessionId就不会被保存下来,也就是说,每一次的请求服务器就会以为是一个新的人

web项目通过ajax提交数据太大报错

ajax提交数据很多的时候报错,web后端没有接收到数据解决方案:经查为tomcat默认限制post提交2M数据。这里需要修改tomcat中大配置文件server.xml文件

ajax的优缺点

ajax异步的js和XML:以前更多的是使用XML的数据格式,现在数据格式更多的是json.;ajax的优势:单页面应用(SPA)无刷新更新数据(局部刷新);异步与服务器通信

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!