首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >自己原生js封装的ajax请求

自己原生js封装的ajax请求

作者头像
无道
发布2019-11-13 14:28:27
3.8K0
发布2019-11-13 14:28:27
举报
文章被收录于专栏:无道编程无道编程

前言

这几天在恶(xue)补(xi)node.js,其中老师讲到了ajax,以前学习js都是东一点、西一点。不系统,当然,原因也很多。

当时一些js基础知识也欠缺(虽然现在也不咋的),想要自己封装,难度也很大。

今天也终于自己封装一个简易 的ajax。

细节

发送POST数据,需要设置header头:

Content-Type 头部信息设置为 application/x-www-form-urlencoded

ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

完整代码参考:

(function (w) {
    var responseType = function (type, content) {
        switch (type) {
            case 'TEXT':
                return content;
            case 'JSON':
                return JSON.parse(content);
            default:
                return content;
        }
    };

    var param = function (a) {
        var s = [],
            rbracket = /\[\]$/,
            isArray = function (obj) {
                return Object.prototype.toString.call(obj) === '[object Array]';
            },
            add = function (k, v) {
                v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v;
                s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v);
            },
            buildParams = function (prefix, obj) {
                var i, len, key;

                if (prefix) {
                    if (isArray(obj)) {
                        for (i = 0, len = obj.length; i < len; i++) {
                            if (rbracket.test(prefix)) {
                                add(prefix, obj[i]);
                            } else {
                                buildParams(prefix + '[' + (typeof obj[i] === 'object' ? i : '') + ']', obj[i]);
                            }
                        }
                    } else if (obj && String(obj) === '[object Object]') {
                        for (key in obj) {
                            buildParams(prefix + '[' + key + ']', obj[key]);
                        }
                    } else {
                        add(prefix, obj);
                    }
                } else if (isArray(obj)) {
                    for (i = 0, len = obj.length; i < len; i++) {
                        add(obj[i].name, obj[i].value);
                    }
                } else {
                    for (key in obj) {
                        buildParams(key, obj[key]);
                    }
                }
                return s;
            };

        return buildParams('', a).join('&').replace(/%20/g, '+');
    };

    async function ajax(options) {
        options.method = options.method ? options.method.toUpperCase() : 'GET';
        options.dataType = options.dataType ? options.dataType.toUpperCase() : 'TEXT';
        options.data = options.data ? options.data : '';

        options.success = options.success ? options.success : function () {
        };
        options.fail = options.fail ? options.fail : function () {
        };
        if (!options.url) {
            throw new Error("there are no url.");
        }

        var ajax = new XMLHttpRequest();
        ajax.open(options.method, options.url, true);
        if (options.method === 'POST') {
            ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            ajax.send(typeof options.data === 'object' ? param(options.data) : options.data);
        } else {
            ajax.send();
        }
        ajax.onreadystatechange = function () {
            if (ajax.readyState === 4) {
                if (ajax.status === 200 || ajax.status === 301) {
                    options.success(responseType(options.dataType, ajax.responseText));
                } else {
                    throw new Error("the status of this request is't done.");
                }
            }

        };
    }

    w.ajax = ajax;

})(window);

其中param函数是参考:https://www.cnblogs.com/daysme/p/6651382.html

目的是发送post时,如果data参数是对象,那么将其转换为字符串类型。

使用

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <script src="ajax.js"></script>
    <script>
        window.onload = function () {
            let oBtn = document.getElementById('btn');
            oBtn.onclick = function () {
                ajax({
                    url: 'http://localhost:3000',
                    method: 'post',
                    data: 'aa=ff&dd=afjalk',
                    success: function (res) {
                        console.log(res);
                    },
                    dataType: 'json'
                })

            };

        };
    </script>
</head>
<body>
<button id="btn">Request</button>
</body>
</html>

核心就是:

ajax({
    url: 'http://localhost:3000',
    method: 'post',
    data: 'aa=ff&dd=afjalk', // data可以是这种字符串,也可以是对象{}
    success: function (res) {
        console.log(res);
    },
    dataType: 'json'
})

压缩文件下载:ajax.min.js

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 细节
  • 使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档