原生Javascript的Ajax方法

不使用jQuery的Ajax方法,类似jQuery的$.ajax方法

function Ajax(type, url, data, success, failed){

// 创建ajax对象

var xhr = null;

if(window.XMLHttpRequest){

xhr = new XMLHttpRequest();

} else {

xhr = new ActiveXObject('Microsoft.XMLHTTP')

}

var type = type.toUpperCase();

// 用于清除缓存

var random = Math.random();

if(typeof data == 'object'){

var str = '';

for(var key in data){

str += key+'='+data[key]+'&';

}

data = str.replace(/&$/, '');

}

if(type == 'GET'){

if(data){

xhr.open('GET', url + '?' + data, true);

} else {

xhr.open('GET', url + '?t=' + random, true);

}

xhr.send();

} else if(type == 'POST'){

xhr.open('POST', url, true);

// 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.send(data);

}

// 处理返回数据

xhr.onreadystatechange = function(){

if(xhr.readyState == 4){

if(xhr.status == 200){

success(xhr.responseText);

} else {

if(failed){

failed(xhr.status);

}

}

}

}

}

评论

Popular Posts

《活法》作者:[日]稻盛和夫 pdf下载

浩方对战平台优化版 V2.05 部分去除浩方广告和弹出窗口

麦当劳免费Wifi帐号密码及连接设置

Microsoft 365安装包下载(Office桌面应用)

中兴ZTE H618B 路由器固件刷机备忘

Debian 12上使用Nginx代理TCP流量,并配置IPv6白名单访问控制

解决word和excel运行时错误:91未设置对象变量或with block变量

MIFARE Classic Tool - 安卓NFC门禁卡修改工具

MD大战略2 德国闪击战 中文汉化版