w3pop.com :: ÍøÂçѧԺ :: AJAX :: AJAX Êý¾Ý¿â
AJAX can be used for interactive communication with a database.
AJAX¿ÉÒÔÓÃÀ´ºÍÊý¾Ý¶Ë½øÐÐÊý¾ÝµÄ½»»¥ÁªÍ¨¡£
In the AJAX example below we will demonstrate how a web page can fetch information from a database using AJAX technology.
ÔÚÒÔϵÄAJAX·¶ÀýÖУ¬ÎÒÃÇ¿ÉÒÔÁ˽⵽һ¸öÍøÒ³ÊÇÈçºÎÓÃAJAX¼¼Êõ´ÓÊý¾Ý¶Ë»ñµÃÐÅÏ¢µÄ¡£
The example above contains a simple HTML form and a link to a JavaScript:
ÉÏÃæµÄÀý×Ó°üº¬ÁËÒ»¸ö¼òµ¥µÄHTML±íµ¥ºÍÒ»¹ØÁªµ½JSµÄlink:
<html> <body> <form> <p> </body> |
As you can see it is just a simple HTML form with a drop down box called "customers".
ÕýÈçÄãËù¼ûÕâÖ»ÊÇÒ»¸ö¼òµ¥µÄHTML±íµ¥£¬ÀïÃæÓÐÒ»¼òµ¥µÄÏÂÀ²Ëµ¥£¬ÆäÃû³ÆÎª"customers"
The paragraph below the form contains a div called "txtHint". The div is used as a placeholder for info retrieved from the web server.
±íµ¥ÏÂÃæ°üº¬Ò»¸öÃûΪ"txtHint"µÄDIV£¬¸ÃDIV±»ÓÃÀ´×öΪ·´À¡´ÓWEB·þÎñÆ÷¼ìË÷ÐÅÏ¢µÄռλ·û
When the user selects data, a function called "showCustomer()" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showCustomer is called.
µ±Óû§Ñ¡ÔñÊý¾Ý£¬Ò»¸ö³ÆÎª "showCustomer()"µÄº¯Êý±»Ö´ÐÐÁË¡£Õâ¸öº¯ÊýÓÉ"onchange"ʼþËù´¥·¢¡£¿ÉÒÔÕâô½²£ºÃ¿µ±Óû§¸Ä±äÏÂÀ²Ëµ«ÖеÄÃû×Ö£¬º¯Êý¾Í»áÖ´ÐÐ
The JavaScript code is listed below.
JSµÄ´úÂëÔÚÏÂÃæ
This is the JavaScript code stored in the file "selectcustomer.js":
ÕâÊÇJS´úÂ룬±»±£´æÔÚÒ»½Ð×ö"selectcustomers.js"µÄÎļþÄÚ£º
var xmlHttp |
The server paged called by the JavaScript, is a simple ASP file called "getcustomer.asp".
·þÎñÒ³ÓÉJSËùµ÷Dz£¬ÊÇÒ»³ÆÎª"gecustomer.asp"µÄ¼òµ¥ASPÎļþ
The page is written in VBScript for an Internet Information Server (IIS). It could easily be rewritten in PHP, or some other server language.
¸ÃҳʹÓõÄÊÇÕë¶ÔIISµÄVBSÓïÑÔ£¬µ±È»Ò²¿ÉÒÔ¸Äд³ÉÏñPHP»òÊÇÆäËûһЩ·þÎñÓïÑÔ
The code runs an SQL against a database and returns the result as an HTML table:
´úÂëÔËÐÐÁËSQLÀ´´ÓÊý¾Ý¿âÖн«½á¹û·µ»Øµ½HTML±í¸ñÖУº
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID=" |