IT兄弟連 JavaWeb教程 使用AJAX發送POST請求並獲取響應

POST請求用於向服務器發送應該被保存的數據,所以POST請求自然比GET請求多須要一份須要被保存的數據。那麼這些數據應該放在何處呢?畢竟,咱們的open()方法接收的三個參數都沒有合適的位置。ajax

答案是須要發送的數據會做爲send()方法的參數最終被髮往服務器,該數據能夠是任意大小,任意類型。服務器

使用Ajax發送POST請求須要使用setRequestHeader()方法設置請求頭,代碼以下:app

function PostRequest(){函數

    var xhr = null;post

    if(window.XMLHttpRequest){url

         xhr = new XMLHttpRequest();code

    }else{orm

         xhr = new ActiveXObject("Microsoft.XMLHttp");對象

    }回調函數

    xhr.open('post,’/ajax_demo’,true);

    xhr.setRequestHeader('Content-Type’,"application/x-www-form-urlencoded’);

    xhr.onreadystatechange = function(){

         if(xhr.readyState == 4 && xhr.status == 200){

              var data = xhr.responseText;

         }

    }

    xhr.send('username=itxdl;password=123456’);

}

總結:

●  建立XHR對象 var xhr = new XMLHttpRequest()或var xhr = new ActiveXObject ("Microsoft.XMLHttp")。

●  創建HTTP鏈接 xhr.open('GET’,URL,ASYNC)。

●  設置請求頭 xhr.setRequestHeader('Content-Type’,’application/x-www-form-urlencoded’)。

●  給XHR狀態綁定一個回調函數 xhr.onreadystatechange = function(){}。

●  在回調函數中判斷Ajax的狀態是否等於4,HTTP狀態碼是否等於200,而後編寫相應的業務邏輯。

●  發送一個HTTP請求 xhr.send(data);

相關文章
相關標籤/搜索