AJAX
AJAX
- AJAX = Asynchronous JavaScript And XML.
- Update a web page without reloading the page
- Send data to a web server - in the background
- A browser built-in XMLHttpRequest object (to request data from a web server)
-
AJAX XML Example
-
<!DOCTYPE html> <html> <body> <h2>The XMLHttpRequest Object</h2> <button type="button" onclick="loadDoc()">Get my CD collection</button> <br><br> <table id="demo"></table> <script> function loadDoc() { var xhttp = new XMLHttpRequest(); //XMLHttpRequest: AJAX主要物件,透過此物件與server端傳遞資訊 xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "cd_catalog.xml", true); //透過方法"GET",給server端 xhttp.send(); } function myFunction(xml) { var i; var xmlDoc = xml.responseXML; //取得xml內XML的資料 var table="<tr><th>Artist</th><th>Title</th></tr>"; var x = xmlDoc.getElementsByTagName("CD"); //取XML內Tag為CD for (i = 0; i <x.length; i++) { table += "<tr><td>" + x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue + //CD > ARTIST > Value "</td><td>" + x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + //CD > TITLE > Value "</td></tr>"; } document.getElementById("demo").innerHTML = table; //塞入demo內 } </script> </body> </html>
AJAX Database Example
-
<!DOCTYPE> <html> <body> <form action=""> <select name="customers" onchange="showCustomer(this.value)"> <option value="" >Select</option> <option value="ALFKI" >ALFKI </option> <option value="NORTS" >NORTS </option> <option value="WOLZA" >WOLZA </option> </select> </form> <br> <div id="txtHint">Customer...</div> <script> function showCustomer(str){ var xhttp; if (str == "") { document.getElementById("txtHint").innerHTML=""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function (){ if (this.readyState == 4 && this.status == 200){ document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("GET","getcustomer.asp?q="+str,true) xhttp.send(); }; </script> </body> </html>
參考網址: AJAX XML、AJAX Database
推薦網址說明: AJAX