原生JS前端开发中Ajax实例的方法

web前端ajax开发面试题|前端ajax快速开发框架|前端开发的开源工具包

javascript 代码

function ajax() {
    var ajaxData = {
        type: arguments[0].type || “GET”,
        url: arguments[0].url || “”,
        async: arguments[0].async || “true”,
        data: arguments[0].data || null,
        dataType: arguments[0].dataType || “text”,
        contentType: arguments[0].contentType || “application/x-www-form-urlencoded”,
        beforeSend: arguments[0].beforeSend || function () {},
        success: arguments[0].success || function () {},
        error: arguments[0].error || function () {}
    }
    ajaxData.beforeSend()
    var xhr = createxmlHttpRequest();
    xhr.responseType = ajaxData.dataType;
    xhr.open(ajaxData.type, ajaxData.url, ajaxData.async);
    xhr.setRequestHeader(“Content-Type”, ajaxData.contentType);
    xhr.send(convertData(ajaxData.data));
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                ajaxData.success(xhr.response)
            } else {
                ajaxData.error()
            }
        }
    }
}
function createxmlHttpRequest() {
    if (window.ActiveXObject) {
        return new ActiveXObject(“Microsoft.XMLHTTP”);
    } else if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
}
function convertData(data) {
    if (typeof data === ‘object’) {
        var convertResult = “”;
        for (var c in data) {
            convertResult += c + “=” + data[c] + “&”;
        }
        convertResult = convertResult.substring(0, convertResult.length – 1)
        return convertResult;
    } else {
        return data;
    }
}

使用格式跟jquery的ajax差不多:
javascript 代码

ajax({
    type: “POST”,
    url: “ajax.php”,
    dataType: “json”,
    data: {
        “val1”: “abc”,
        “val2”: 123,
        “val3”: “456”
    },
    beforeSend: function () {
        //some js code
    },
    success: function (msg) {
        console.log(msg)
    },
    error: function () {
        console.log(“error”)
    }
})

菜鸟前端开发的的工作|前端开发有几个岗位|web 前端开发岗位职责

» 本文来自:前端开发者 » 《原生JS前端开发中Ajax实例的方法》
» 本文链接地址:https://www.rokub.com/3850.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!