var xhr = new ActiveXObject(‘Msxm12.XMLHTTP‘)创建xhr.readyState == 4 && xhr.status == 200表示请求成功json.parsefunction ajax(options){
//默认值的处理,用户不传某些参数的时候,设置一些默认值
//设置type的默认值为get
options.type = options.type || "get";
//设置请求地址的默认值为当前页地址
options.url = options.url || location.href;
// //设置async的默认值
options.async = options.async || "true";
//设置options.data的默认值
options.data = options.data || {};
//处理用户传进来的请求参数(data)对象
//{key: "123", age: 1, gender: "male"}
//key=123&age=1&gender=male
var dataArr = [];
for(var k in options.data){
dataArr.push(k + "=" + options.data[k]);
}
var dataStr = dataArr.join("&");
var xhr = new XMLHttpRequest();
xhr.open(options.type, options.type == "get"? options.url + "?" + dataStr : options.url, options.async);
if(options.type == "post"){
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
xhr.send(options.type == "get"? null : dataStr);
if(options.async){
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var type = xhr.getResponseHeader("Content-Type");
var result;
if(type.indexOf("json") != -1){
result = JSON.parse(xhr.responseText);
}else if(type.indexOf("xml") != -1){
result = xhr.responseXML;
}else{
result = xhr.responseText;
}
options.success(result);
}
}
}else{
var type = xhr.getResponseHeader("Content-Type");
var result;
if(type.indexOf("json") != -1){
result = JSON.parse(xhr.responseText);
}else if(type.indexOf("xml") != -1){
result = xhr.responseXML;
}else{
result = xhr.responseText;
}
options.success(result);
}
}
function get(options){
options.type = "get";
ajax(options);
}
function post(options){
options.type = "post";
ajax(options);
}
// ajax({
// url: "json.php",
// data: {key: "123", age: 1, gender: "male"},
// success: function(data){
// console.log(data);
// }
// });
get({
url: "json.php",
success: function(data){
console.log(data);
}
})
// ajax({
// url: "xml.php",
// type: "get",
// data: {key: "123", age: 1, gender: "male"},
// success: function(data){
// console.log(data);
// }
// });
原文:http://www.cnblogs.com/ddduck/p/7413972.html