Ajax不是一種新的編程語言,而是一種用于創建更好更快以及交互性更強的Web應用程序的技術。通過Ajax,您可以使用 JavaScript的XMLHttpRequest對象來直接與服務器進行通信。您可以在不重載頁面的情況與 Web 服務器交換數據。在本文的例子中,我們將演示當用戶向一個標準的HTML表單中輸入數據時網頁如何與web服務器進行通信。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>簡單的Ajax請求</title> <script type="text/javascript"> var xmlHttp; // 創建XMLHttpRequest對象 function createXMLHttpRequest() { if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } } // 整合url參數 function createQueryString() { var name = document.getElementById("txtName").value; var sex = document.getElementById("txtSex").value; var birthday = document.getElementById("txtBirthday").value; var queryString = "Name=" + encodeURIComponent(name) + "&Sex=" + encodeURIComponent(sex) + "&Birthday=" + encodeURIComponent(birthday); return queryString; } // 按照Get方式傳遞參數 function doRequestUsingGET() { createXMLHttpRequest(); var queryString = "AjaxServer.ashx?"; queryString = queryString + createQueryString() + "&timeStamp=" + new Date().getTime(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET", queryString, true); xmlHttp.send(null); } // 按POST方式傳遞參數 function doRequestUsingPOST() { createXMLHttpRequest(); var url = "AjaxServer.ashx?timeStamp=" + new Date().getTime(); var queryString = createQueryString(); xmlHttp.open("POST", url, true); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); xmlHttp.send(queryString); } // 回調函數 function handleStateChange() { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { parseResults(); } } } // 處理服務器響應內容 function parseResults() { var responseDiv = document.getElementById("serverResponse"); if (responseDiv.hasChildNodes()) { responseDiv.removeChild(responseDiv.childNodes[0]); } var responseText = document.createTextNode(xmlHttp.responseText); responseDiv.appendChild(responseText); } </script></head><body> <form action="#"> <h2>輸入你的名字,性別,生日:</h2> <table> <tr><td>名字:</td><td><input type="text" id="txtName" /></td></tr> <tr><td>性別:</td><td><input type="text" id="txtSex" /></td></tr> <tr><td>生日:</td><td><input type="text" id="txtBirthday" /></td> </tr> </table> <input type="button" value="用Get方式傳參數" onclick="doRequestUsingGET();"/> <br /><br /> <input type="button" value="用POST方式傳參數" onclick="doRequestUsingPOST();"/> </form> <br /> <h3>服務器響應內容:</h3> <div id="serverResponse"></div></body></html>
新聞熱點
疑難解答
圖片精選