原生的ajax:
创建 XMLHttpRequest 对象
try{
xhr = new XMLHttpRequest;
}catch(e){
xhr = new ActiveObject(“Microsoft.XMLHTTP”)
}xhr.open(type,url,asyns) 规定请求数据的类型,地址,以及是否异步(false)
type: ‘get’/’post’等
url: 发送请求地址
asyns: true/false(默认异步)回调函数:
xhr.onreadystatechange = function (){
//当请求发送到服务器时,做一些响应
}- xhr.send(); 将请求发送发到服务器上
1.> type = ‘get’ ; xhr.send(null);
2.> type = ‘post”;
xhr.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);
xhr.send(param); //param: 要发送的数据
- xhr.send(); 将请求发送发到服务器上
如: 封装了一个函数;
function myAjax(data){
// 定义对象
var xhr = null;
// 做兼容性
try{
xhr = new XMLHttpRequest();
}catch(e){
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var type = data.type == 'get' ? 'get' :'post';
var url = data.url;
var flag = data.asny == 'true'?'true':'false';
xhr.open(type,url,flag);
// 发送
if(data.type == 'get'){
// 发送null , 是为了兼容老版的浏览器
xhr.send(null);
}else if(data.type == 'post'){
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(data.data);
}
// 回调函数
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
if(xhr.status == 200){
if(typeof data.success == 'function'){
var d = data.dataType == 'xml' ? xhr.responseXML : xhr.responseText;
data.success(d);
}
}else if(typeof data.failure == 'function'){
data.failure();
}
}
}
}