码迷,mamicode.com
首页 > Web开发 > 详细

简单封装一个ajax插件

时间:2019-01-29 23:04:18      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:enc   success   hang   cat   xhr   ext   for   The   ready   

function ajax(options) {
    options = options || {};
    options.type = options.type || get;
    options.type = options.data || {};
    options.dataType = options.dataType || text;


    //IE6以下无法使用
    let xhr = new XMLHttpRequest();
    // 数据修改
    let arr = [];
    for (let name in options.data) {
        arr.push(`${name}=${options.data[name]}`)
    }
    let strData = arr.join(&);
    if (options.type == post) {
        xhr.open(post, options.url, true);
        xhr.setRequestHeader(content-type, application/x-www-form-urlencoded)
        xhr.send(strData);
    } else {
        xhr.open(get, options.url + ? + strData, true);
        xhr.send();
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                let data = xhr.responseText;
                switch (options.dataType) {
                    case json:
                        if (window.JSON && JSON.parse) {
                            data = JSON.parse(data);
                        } else {
                            data = eval(( + str + ))
                        }
                        break;
                    case xml:
                        data = xhr.responseXML;
                        break
                }
                options.success && options.success(data);
            } else {
                options.error && options.error()
            }
        }
    }
}

 

简单封装一个ajax插件

标签:enc   success   hang   cat   xhr   ext   for   The   ready   

原文地址:https://www.cnblogs.com/yang656/p/10336003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!