原生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

女生可以对男朋友心机到什么程度?(苦)

网站建设公司不挣钱的原因

Wenger 单肩包

LAMP网站架构方案分析

流浪猫鲍勃 A Street Cat Named Bob (2016)

会声会影 X7旗舰简体珍藏版

小兵 封装专用母盘 XPLITE-V8 第四版

如何提高自己的领悟力

移动联通电信年底积分兑换话费(防止清零)

《贫穷的本质(修订版)》阿比吉特·班纳 & 埃斯特·迪弗洛