Javascript封装原生ajax请求

2017-11-30 20:00:02来源:CSDN作者:qq_28626551人点击

分享
function ajax() {    var param = {        url: arguments[0].url || '',        type: arguments[0].type || "Get",        data: arguments[0].data,        dataType: arguments[0].dataType || "json",        contentType: arguments[0].contentType || "application/x-www-form-urlencoded",        async: arguments[0] || true,        beforSend: arguments[0].beforeSend || function () { },        success: arguments[0].success || function () { },        error: arguments.error || function () { },        complete: arguments[0].complete || function () { }    }    param.beforSend();    var xmlhttpRequest = createHttpRequest();    xmlhttpRequest.responseType = param.dataType;    xmlhttpRequest.open(param.type, param.url, param.async);    xmlhttpRequest.setRequestHeader("Content-Type", param.contentType);    xmlhttpRequest.send(converData(param.data));    xmlhttpRequest.onreadystatechange = function () {        if (xmlhttpRequest.readyState === 4) {            if (xmlhttpRequest.status === 200) {                param.success(xmlhttpRequest.response);            } else {                param.error();            }            param.complete();        }    }}//创建请求对象function createHttpRequest() {    if (window.ActiveXObject) {        return new ActiveXObject("Microsoft.XMLHTTP");    } else if (window.XMLHttpRequest) {        return new XMLHttpRequest();    } else {        return null    }}//解析请求参数function converData(dataPar) {    if (typeof dataPar === 'object') {        var result = "";        for (var i in dataPar) {            result += i + '=' + dataPar[i] + "&"        }        result = result.substring(0, result.length - 1);        return result;    } else {        return dataPar;    }}

相关文章

    无相关信息

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台