ajax怎么转换js,如何将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 += encodeURIComponent(x)+"="+encodeURIComponent(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-urlencoded; charset=UTF-8");

xhr.send(option.data);

} else {

xhr.open(option.type, option.url+option.data, true);

xhr.send(null);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值