本文以實例說明如何以 JavaScript 透過 Ajax 實現不刷新動態顯示檔案內容,分享給大家參考。具體如下:
下面的 JS 程式碼是最基礎的 Ajax 實現,可以動態顯示伺服器上 ajax_info.txt 檔案的內容。
<!DOCTYPE html> <html> <head> <title>sharejs.com</title> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
這段程式碼示範了 Ajax 最核心的用法:建立 XMLHttpRequest 物件、以 GET 請求讀取伺服器上的文字檔,並在 readyState 為 4 且 status 為 200 時,把 responseText 寫入頁面的指定元素,从而实现點擊按鈕就能更新內容而不必刷新整頁。希望本文所述對大家的 Ajax 程式設計有所幫助。