一个比较完整的XMLHttpRequest

134 阅读1分钟
  • 只支持异步
  • token自行处理
  • 返回数据自行处理
/**
 * 必须是异步请求
 * @param {Object} method
 * @param {Object} url
 * @param {Object} data
 * @desc 
 * 如果data是 Document 类型,同时也是HTML Document类型,则content-type默认值为text/html;charset=UTF-8;否则为application/xml;charset=UTF-8;
 * 如果data是 DOMString 类型,content-type默认值为text/plain;charset=UTF-8;
 * 如果data是 FormData 类型,content-type默认值为multipart/form-data; boundary=[xxx]
 * 如果data是其他类型,则不会设置content-type的默认值
 */
sendAjax(method, url, data, token) {
    return new Promise((resolve, reject) => {
        //创建xhr对象 
        var xhr = new XMLHttpRequest()
        //设置xhr请求的超时时间
        xhr.timeout = 60000;
        //设置响应返回的数据格式
        xhr.responseType = "text"
        //创建一个请求,采用异步
        xhr.open(method, url, true)
        // 设置request header
        xhr.setRequestHeader('token', token)
        //注册相关事件回调处理函数
        xhr.onreadystatechange = (e) => {
            if (xhr.readyState === 4) {
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                    let response = ''
                    if (xhr.responseType === 'application/json') {
                        response = JSON.parse(xhr.responseText) // JSON响应
                    } else {
                        response = xhr.responseText // 字符串响应
                    }
                    resolve(response)
                }
            }
        }
        xhr.ontimeout = function(e) {
            reject({ status: 'ontimeout', message: e })
        };
        xhr.onerror = function(e) {
            reject({ status: 'error', message: e })
        }
        // 断网判断
        try {
            xhr.send(data) // 发送数据
        } catch(e) {
            reject({ status: 'sendError', message: 'Uncaught NetworkError' })
        }
        // return false // 防止页面提交
    })
}
const fd = new FormData()
fd.append('task.taskId', 902949)
const token = 'SbqrpWOkrkI6tnWpHQwZxrYqfkLL01hF5WwMMKVpJHk='
this.sendAjax('POST', 'http://test.zhihuihedao.cn:8084/patrolManageAction!eachJsonFinishTask0711_Andorid_1p4_IOS4.action', fd, token).then(res => {
        console.log(res)
}).catch(err => {
        console.log(err)
})

参考: