Js之AJAX简易封装

2017-12-01 20:14:45来源:CSDN作者:qq_24729895人点击

分享

提供对原生ajax的简易封装

/* * 封装ajax库 * author: wenqian * email: 843462167@qq.com */(function() {    /*     * 创建 XMLHttpRequest 对象的语法     * XMLHttpRequest IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码     * ActiveXObject IE6, IE5 浏览器执行代码     */    var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : ActiveXObject("Microsoft.XMLHTTP")    // 配置    var config = {        url: '',        method: 'get',        headers: {            'Content-Type': 'application/json'        },        // 提供path query选项        getParamsWhere: 'query'    }    /*     * 发送请求     * url 请求地址     * method 请求方式     * params 参数     * headers 头部信息     */    var send = (method = config.method, url, params, headers = config.headers) => {        console.log(headers)        // 设置header        return new Promise((resolve, reject) => {            // url不存在时候            if (!url) return reject(response('url错误', 'error'))            try {                xhr.open(method, url, true)                if (headers && typeof headers === 'object') {                    for (var head in headers) xhr.setRequestHeader(head, headers[head])                }                xhr.send(params ? JSON.stringify(params) : '')                xhr.onerror = (error) => {                    return reject(response(error, 'error'), xhr.status)                }                xhr.onreadystatechange = () => {                    if (xhr.readyState === 4 && xhr.status === 200) {                        return reject(response(JSON.parse(xhr.responseText), 'success'), xhr.status)                    }                }            } catch (e) {                return reject(response(e, 'error'))            }        })    }    /*     * params 必须为对象 可传可不传参     * isQuery querypath 参数     */    var get = (url, params, headers, isQuery = config.getParamsWhere) => {        return send('GET', delUrl(url, params, isQuery), '', headers)    }    var post = (url, params, headers) => {        return send('POST', params, headers)    }    // 处理url 返回query传参,或者path传参    var delUrl = (url,params, isQuery) => {        // 处理url        var str = ''        if (typeof params === 'object') {            for (var i in params) {                str += `${i}=${params[i]}&`            }        } else {            str = ''        }        str = str.substr(0, str.length - 1)        isQuery === 'query' ? str = `?${str}` : isQuery === 'path'? str = `/${str.replace(/&|=/g, '/')}` : str = ''        url = url + str        return url    }    // 处理返回数据    var response = (data, status = 'success', code = '200') => {        return typeof data === 'string' ? { message: data, status: status, code: code } :        { data: data, status: status, code: code }    }    // 调用    get('http://127.0.0.1/shop/public/index.php/index/Books/getBooks', { createtime: '2017-11' }).then(res => {        console.log(res)    }).catch(res => {        console.log(res)    })})()

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台