AJAX and XMLLOGIN

AJAX and XML

AJAX and XML examples:

The following example will demonstrate how a web page reads information from an XML file through AJAX:

                                                                                       

#This example consists of three parts

l HTML form page

l PHP page

l XML file

HTML form page

When the user selects a CD in the drop-down list above, the function named "showCD()" will be executed. This function is triggered by the "onchange" event:

QQ截图20161009174933.png



##After the user selects the drop-down list. Call the showCD() function

ShowCD() function to perform the following steps:

l Check whether a CD is selected

l Create an XMLHttpRequest object

l Create Function executed when the server response is ready

l Send a request to a file on the server

l Please note the parameter (q) added to the end of the URL (containing the contents of the drop-down list)

PHP file

The server page called through JavaScript above is a PHP file named "2.php".

The PHP script loads the XML document, "3.xml", runs the query against the XML file, and returns the results in HTML:

QQ截图20161009174957.png


When the CD query is sent from JavaScript to the PHP page, what happens:

l PHP creates the XML DOM object of the "3.xml" file

l Loop through all "artist" elements (nodetypes = 1), find the name that matches the data transmitted by JavaScript

l Find the correct artist included in the CD

l Output the album information and send it To "txtHint" placeholder

XML file

QQ截图20161009175012.png


##The file Contains data about CD collection

Next Section
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function showCD(str){ if(str==""){ document.getElementById("txt").innerHTML=""; return; } if(window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行 xmlhttp=new XMLHttpRequest(); }else{ //IE6,IE5浏览器执行 xmlhttp =new ActiveXObject("MIcrosoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4&&xmlhttp.status==200){ document.getElementById("txt").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","8_2.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> 选择一个CD: <select name="cds" onchange="showCD(this.value)"> <option value="Bob Dylan">Bob Dylan</option> <option value="Bonnie Tyler">Bonnie Tyler</option> <option value="Dolly Parton">Bonnie Tyler</option> </select> </form> </br> <div id="txt"><b>选择下拉列表,显示详细信息</b></div> </body> </html>
submitReset Code
ChapterCourseware