以前學習過如何用原生的javascript實現ajax,但是久了不用就忘記了,今天來鞏固一下,直接上代碼:
//創建ajax對象
ajax = (url,method,data) => {
var http = window.XMLHttpRequest? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
//爲了兼容ie6
http.onreadystatechange = () => {
//readyState狀態改變事件
if(http.readyState == 4){
if(http.status == 200){
//對http.responseText處理
}
else {
//錯誤處理
}
}
}
if(typeof data == 'object'){
//判斷傳進來的參數是不是對象
let str = '';
for(let key in data){
str += key+'='+data[key]+'&';
}
data = str.replace(/&$/, '');
}
let random = Math.floor(Math.random()*10); //生成0-10隨機數並整數化,目的是清除緩存
if (method == 'GET'){ //判斷是不是get方法
if (data){
http.open('GET',url+'?'+data,true);
}
else{
http.open('GET',url+'?t='+random,true);
}
http.send();
}
else{ 如果是post方法
http.open('POST',url,true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//設置請求頭信息
http.send(data);
}
}