栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将jquery ajax转换为本机javascript?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将jquery ajax转换为本机javascript?

我提取了Jquery的ajax函数,无需使用jquery就可以工作。

并替换

$.ajax(attributes);
ajax(attributes);

没有JQuery的JQuery的ajax函数:

function ajax(option) { // $.ajax(...) without jquery.    if (typeof(option.url) == "undefined") {        try { option.url = location.href;        } catch(e) { var ajaxLocation; ajaxLocation = document.createElement("a"); ajaxLocation.href = ""; option.url = ajaxLocation.href;        }    }    if (typeof(option.type) == "undefined") {        option.type = "GET";    }    if (typeof(option.data) == "undefined") {        option.data = null;    } else {        var data = "";        for (var x in option.data) { if (data != "") {     data += "&"; } data += enpreURIComponent(x)+"="+enpreURIComponent(option.data[x]);        };        option.data = data;    }    if (typeof(option.statusCode) == "undefined") { // 4        option.statusCode = {};    }    if (typeof(option.beforeSend) == "undefined") { // 1        option.beforeSend = function () {};    }    if (typeof(option.success) == "undefined") { // 4 et sans erreur        option.success = function () {};    }    if (typeof(option.error) == "undefined") { // 4 et avec erreur        option.error = function () {};    }    if (typeof(option.complete) == "undefined") { // 4        option.complete = function () {};    }    typeof(option.statusCode["404"]);    var xhr = null;    if (window.XMLHttpRequest || window.ActiveXObject) {        if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } }        else { xhr = new XMLHttpRequest(); }    } else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; }    xhr.onreadystatechange = function() {        if (xhr.readyState == 1) { option.beforeSend();        }        if (xhr.readyState == 4) { option.complete(xhr, xhr.status); if (xhr.status == 200 || xhr.status == 0) {     option.success(xhr.responseText); } else {     option.error(xhr.status);     if (typeof(option.statusCode[xhr.status]) != "undefined") {         option.statusCode[xhr.status]();     } }        }    };    if (option.type == "POST") {        xhr.open(option.type, option.url, true);        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlenpred; charset=UTF-8");        xhr.send(option.data);    } else {        xhr.open(option.type, option.url+option.data, true);        xhr.send(null);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/373800.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号