原生JS的Ajax
轉自:https://www.cnblogs.com/yufann/p/JS-Ajax.html
1.創建一個Ajax對象
非IE6瀏覽器:var obj = new XMLHttpReuqest();
IE6瀏覽器:var obj = new ActiveXbject("Microsoft.XMLHTTP");
2.連接到服務器
obj.open(請求方式,url,是否異步)
阻止緩存方式:
obj.open(‘get‘,‘yan.txt?name=‘+new Date().getTime(),true);
3.發送請求
obj.send();
4.接收返回值
請求狀態監控:onreadystatechange事件:當自己的Ajax與服務器之間有通訊時觸發
主要通過readyState屬性來判斷有沒有結束,結束了也並沒有成功,status屬性來判斷
1.----readyState屬性:請求狀態
0(未初始化)還沒有調用send()方法
1(載入)已經調用了send()方法,正在發送請求
2(載入完成)send()方法執行完成,已經接收到全部響應內容
3(交互)正在解析響應內容
4(完成)響應內容解析完成,可以在客戶端調用了(完成不一定成功,需要status來檢測是否成功)
2.---status屬性:請求結果,是成功(200)還是失敗(404):obj.status==200
3.---返回值responseText:從服務器返回的文本:obj.responseText(返回的為字符串)
GET方式
function getAjax(){ var obj; if(ActiveXObject)//判斷是否是IE6 obj = newActiveXObject("Microsoft.XMLHTTP"); else obj = new XMLHttpRequest(); //連接服務器 obj.open(‘get‘,‘http://localhost:8080/yan.ashx?name=123‘,true); //發送請求 obj.send(); obj.onreadystatechange=function(){ if(obj.readyState===4&&obj.status===200)//如果接收完成並且請求成功 console.log(obj.responseText);//輸出返回信息 } }
POST方式
function postAjax(){ var obj; if(ActiveXObject)//判斷是否是IE6 obj = new ActiveXObject(‘Microsoft.XMLHTTP‘); else obj =new XMLHttpRequest(); //連接服務器 obj.open(‘post‘,‘http://localhost:8080/yan.ashx?name=123‘,true); //設置頭信息 obj.setRequestHeader(‘Content-type‘,‘application/x-www-form-urlencoded‘); //發送請求,傳遞數據 obj.send({name:‘123‘}); obj.onreadystatechange = function(){ if(obj.readyState===4&&obj.status===200)//如果接收完成並且請求成功 console.log(obj.responseText);//輸出返回信息 } }
原生JS的Ajax