同步交互html
異步交互服務器
<body> <script src="chajian/createXMLHttpRequest.js"></script> <script> /* XMLHttpRequest對象 * XMLHttpRequest對象是Ajax的核心對象 * XMLHttpRequest對象是實現異步交互的核心 */ /* 經過createXMLHttpRequest()方法來建立一個XMLHttpRequest對象 */ var xhr = createXMLHttpRequest(); console.log( xhr );// 獲得一個XMLHttpRequest對象 </script> </body>
建立XMLHttpRequest對象app
調用XMLHttpRequest對象的open()方法異步
open()方法學習
參數url
第一個參數 - 表示當前的請求方式code
調用XMLHttpRequest對象的send()方法orm
send()方法htm
參數對象
利用XMLHttpRequest對象的onreadystatechange事件
onreadystatechange事件
服務器端的通訊狀態中 - 存在着處理完畢(信號)
readyState屬性
屬性值
responseText屬性
將接收到的結果更新到HTML頁面
<body> <button id="btn">按鈕</button> <script src="chajian/createXMLHttpRequest.js"></script> <script> var btn = document.getElementById( 'btn' ); btn.addEventListener( 'click', function () { /* 實現Ajax異步交互 */ /* 1. 建立XMLHttpRequest對象 */ var xhr = createXMLHttpRequest(); /* 2. 調用XMLHttpRequest對象的open()方法 */ /* 經過open()方法來創建與服務器端的關係 */ xhr.open( 'get', 'http://localhost:63342/學習資料/XMLHttpRequest對象.html' ); /*3. 調用XMLHttpRequest對象的send()方法 */ /* 經過send()方法來向服務器端發送數據 */ xhr.send( null ); /* 4. 利用XMLHttpRequest對象的onreadystatechange事件 */ /* 設置onreadystatechange事件 */ xhr.onreadystatechange = function(){ /* 經過readyState屬性來判斷服務器端的狀態 */ if (xhr.readyState === 4) { /* 經過responseText屬性來獲取服務器端的響應結果 */ console.log( xhr.responseText ); } } /* 5. 將接收到的結果更新到HTML頁面 * 經過HTTP協議來完成 */ } ); </script> </body>
XMLHttpRequest對象的readyState屬性
屬性值
XMLHttpRequest對象的status屬性
用於獲得當前請求以後的響應狀態碼
屬性值
responseText屬性
responseXML屬性
<body> <button id="btn">按鈕</button> <script src="chajian/createXMLHttpRequest.js"></script> <script> var btn = document.getElementById( 'btn' ); btn.addEventListener( 'click', function(){ var xhr = createXMLHttpRequest(); xhr.onreadystatechange = function(){ /* 顯示readyState屬性 */ console.log( xhr.readyState ); /* 判斷當前服務器端的狀態 */ if ( xhr.readyState === 4 ) { /* 顯示status屬性 */ console.log( xhr.status ); /* 判斷當前響應狀態 */ if ( xhr.status === 200 ) { /* 顯示responseText屬性 */ console.log( xhr.responseText ); } } /* 能夠同時判斷當前服務器端的狀態和響應狀態 */ if ( xhr.readyState === 4 && xhr.status === 200 ) { /* 顯示responseText屬性 */ console.log( xhr.responseText ); } }; xhr.open( 'get', 'http://localhost:63342/學習資料/XMLHttpRequest對象.html' ); xhr.send( null ); } ); </script> </body>
XMLHttpRequest對象的send()方法
參數
send()方法的參數與當前的請求方式有關
若是當前的請求方式爲 GET
send()方法中只能傳遞 null值
若是當前的請求方式爲 POST
<body> <button id="btn">按鈕</button> <script src="chajian/createXMLHttpRequest.js"></script> <script> var btn = document.getElementById( 'btn' ); btn.addEventListener( 'click',function(){ // 1.建立XMLHttpRequest對象 var xhr = createXMLHttpRequest(); xhr.onreadystatechange = function(){ if ( xhr.readyState === 4 && xhr.status === 200 ) { console.log( xhr.responseText ); } }; xhr.open( 'get', 'http://localhost:63342/學習資料/XMLHttpRequest對象.html' ); /* 設置請求頭部信息 */ xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send( null ); } ); </script> </body>