/* 封装ajax函数
* @param {string}opt.type http连接的方式,包括POST和GET两种方式
* @param {string}opt.url 发送请求的url
* @param {boolean}opt.async 是否为异步请求,true为异步的,false为同步的
* @param {object}opt.data 发送的参数,格式为对象类型
* @param {function}opt.success ajax发送并接收成功调用的回调函数
*/
function ajax(opt) {
opt = opt || {};
opt.method = opt.method.toUpperCase() || 'POST';
opt.url = opt.url || '';
opt.async = opt.async || true;
opt.data = opt.data || null;
opt.success = opt.success || function() {};
var xmlHttp = null;
if(window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
// 新建XMLHttpRequest对象
xmlHttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(opt.method.toUpperCase() === 'POST') {
xmlHttp.open(opt.method, opt.url, opt.async);
xmlHttp.setRequestHeader('Content-Type', opt.contentType ? opt.contentType : 'application/x-www-form-urlencoded;charset=utf-8');
xmlHttp.send(opt.data);
} else if(opt.method.toUpperCase() === 'GET') {
var params = [];
for(var key in opt.data) {
params.push(key + '=' + opt.data[key]);
}
var postData = params.join('&');
xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
xmlHttp.send(null);
}
// onreadystatechange存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
// onreadystatechange 事件被触发 5 次(0 - 4),对应着 readyState 的每个变化
xmlHttp.onreadystatechange = function() {
// readyState存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。0: 请求未初始化; 1: 服务器连接已建立 ; 2: 请求已接收 ; 3: 请求处理中; 4: 请求已完成,且响应已就绪
// status:200: "OK" 404: 未找到页面
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
opt.success(xmlHttp.responseText ? JSON.parse(xmlHttp.responseText) : xmlHttp);
}
// else if(xmlHttp.response && xmlHttp.responseText && xmlHttp.readyState == 3 && xmlHttp.status == 200) {
// opt.success(JSON.parse(xmlHttp.responseText));
// }
else if(xmlHttp.status != 200) {
opt.error(xmlHttp.responseText ? JSON.parse(xmlHttp.responseText) : xmlHttp);
}
};
}