AJAX請求的步驟

一.原生JS請求:
1.創建異步對象:

var xhr = new XMLHttpRequest();

2.設置 請求行 open(請求方式,請求url):

// get請求如果有參數就需要在url後面拼接參數,
// post如果有參數,就在請求體中傳遞 xhr.open("get","validate.php?username="+name)
xhr.open("post","validate.php");

3.設置請求(GET方式忽略此步驟)頭:setRequestHeader():

// 1.get不需要設置
// 2.post需要設置請求頭:Content-Type:application/x-www-form-urlencoded
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

4.設置請求體 send():

// 1.get的參數在url拼接了,所以不需要在這個函數中設置
// 2.post的參數在這個函數中設置(如果有參數)
xhr.send(null) xhr.send("username="+name);

5.讓異步對象接收服務器的響應數據:

xhr.onreadystatechange = function(){ 
if(xhr.status == 200 && xhr.readyState == 4){ 
 console.log(xhr.responseText);
 }

注意:一個成功的響應有兩個條件:1.服務器成功響應了 2.異步對象的響應狀態爲4(數據解析完畢可以使用了)

二.五個步驟連在一起的完整代碼:
1.get:

var xhr = new XMLHttpRequest();
xhr.open("get","validate.php?username="+name);
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState == 4){ console.log(xhr.responseText); document.querySelector(".showmsg").innerHTML = xhr.responseText;;
 }
 }

2.post:

var xhr = new XMLHttpRequest();
xhr.open("post","validate.php");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("username="+name);
xhr.onreadystatechange = function(){
// 判斷服務器是否響應,判斷異步對象的響應狀態
if(xhr.status == 200 && xhr.readyState == 4){
 document.querySelector(".showmsg").innerHTML = xhr.responseText;
 }
 }

三.setRequestHeader的理解:
1.語法

oXMLHttpRequest.setRequestHeader(bstrHeader, bstrValue);
//bstrHeader:字符串,頭名稱。
//bstrValue:字符串,值。
setRequestHeader("Content-type", "application/x-www-form-urlencoded charset=utf-8"); 

setRequestHeader("Content-length", paramsSend.length); //Content-length 就是表示提交的數據字節大小 

setRequestHeader("Connection", "close");//關閉 

通常在HTTP協議裏,客戶端像服務器取得某個網頁的時候,必鬚髮送一個HTTP協議的頭文件,告訴服務器客戶端要下載什麼信息以及相關的參數
eg:

setRequestHeader "a", "b"

雖然IIS不會報錯,但這個信息也可以有用,可以在ASP程序裏讀取HTTP頭信息分析是否有a: b;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章