/**
* readyState 0=未初始化,未调用send()方法
* 1=读取中,已调用send(),正在发送请求
* 2=已读取,send方法执行完成,接收到全部响应内容
* 3=交互中,正在解析响应内容
* 4=完成,响应内容解析完成
*
*
* ajax过程
* 1. 浏览器
* 2. ajax对象
* 3. open() 初始化
* 4. send()
* 5. onreadystatechange
* 6. readystate == 4 && status == 200
*/
function ajax(method, url, data, callback, flag) {
// 创建全平台兼容的XMLHTTPREQUEST对象
function getXHR() {
var xhr = null
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else if(window.ActiveXObject){
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP") // MSXML3
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP") // 兼容IE6, IE5很老的api,虽然浏览器支持,功能不一定完善
} catch(e) {
alert("您的浏览器不支持Ajax!")
}
}
}
return xhr
}
var xhr = getXHR()
var method = method.toUpperCase() // 转换成大写
// 避免加载太快,没监听到事件变换,所以放在这个位置
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback(xhr.responseText)
}
}
}
xhr.onerror = function() {
console.log("error")
}
if (method === 'GET') {
var oDate = new Date(),
timer = oDate.getTime()
xhr.open(method, url+'?'+data+'&timer='+timer, flag)
xhr.send()
} else if(method === 'POST') {
xhr.open(method, url, flag)
xhr.setRequestHeader(''Content-Type', 'application/x-www-form-urlencoded'')
xhr.send(data)
}
}