w3pop.com :: ÍøÂçѧԺ :: AJAX :: AJAX ʵÀý
AJAX can be used to create more interactive applications.
AJAX¿ÉÒÔÓÃÀ´´´½¨½»»¥Ê½ÐÔ¸üºÃµÄÍøÂçÓ¦ÓóÌÐò¡£
In the AJAX example below we will demonstrate how a web page can communicate with a web server online as a user enters data into a web form.
ÔÚÒÔϵÄAJAX·¶ÀýÖУ¬ÎÒÃǽ«Á˽⵽µ±Óû§ÒÔÍøÒ³¸ñʽÊäÈëÊý¾Ýʱһ¸öÍøÒ³ÊÇÈçºÎÓëÍøÂç·þÎñÆ÷Á¬½ÓµÄ¡£
Suggestions:
The form above has the following HTML code:
ÒÔÉϵķ¶ÀýËùº¬³¬Îı¾±ê¼ÇÓïÑÔ´úÂëÈçÏ£º
<form> <p>Suggestions: <span id="txtHint"></span></p> |
As you can see it is just a simple HTML form with an input field called "txt1".
¾ÍÈçÄã¿´µ½µÄ£¬ËüÖ»ÊÇÒ»¸öÆÕͨµÄ±íµ¥£¬ÀïÃæÓÐÒ»³ÆÎª"txt1"µÄÊäÈë¿ò
An event attribute for the input field defines a function to be triggered by the onkeyup event.
ÔÚinputÇøÓòÀïÓÐÒ»¸öʼþÊôÐÔ£¬µ±°´¼üÊͷŵÄʱºò¾Í´¥·¢Õâ¸öʼþ¡£
The paragraph below the form contains a span called "txtHint". The span is used as a placeholder for data retrieved from the web server.
ÏÂÒ»¶Î°üÀ¨ÁËÒ»¸ö³Æ×ö“txtHint”µÄSPAN¡£Õâ¸öSPANÊÇÓÃÀ´´æ´¢´Ó·þÎñÆ÷ÖØÐ»ñµÃµÄÐÅÏ¢µÄ¡£
When the user inputs data, a function called "showHint()" is executed. The execution of the function is triggered by the "onkeyup" event. In other words: Each time the user moves his finger away from a keyboard key inside the input field, the function showHint is called.
µ±Óû§ÊäÈëÊý¾Ý£¬ÃûΪ“showHint()”µÄº¯Êý½«±»Ö´ÐС£Õâ¸öº¯ÊýµÄÖ´ÐÐÊÇÓÉ“onkeyup”ʼþ´¥·¢µÄ¡£»»ÖÖ˵·¨£ºÃ¿µ±Óû§ÔÚtxt1ÇøÓòÄÚ´¥¶¯¼üÅ̰´Å¥£¬showHintÕâ¸öº¯Êý¾Í»áÖ´ÐС£
The showHint() function is a very simple JavaScript function placed in the <head> section of the HTML page.
showHint()º¯ÊýÊÇÒ»ÖÖλÓÚHTML¶¥¶ËµÄ¼òµ¥µÄJSº¯Êý¡£
The function contains the following code:
º¯Êý°üº¬ÒÔÏ´úÂ룺
function showHint(str) |
The function executes every time a character is entered in the input field.
ÿµ±ÓÐ×Ö·û±»¼üÈëÊäÈëÇøÄھͻáÖ´ÐÐÕâ¸öº¯Êý
If there is some input in the text field (str.length > 0) the function executes the following:
ÈçÓÐ×Ö·û±»ÊäÈëÎÄ×ÖÊäÈëÇø(str.length>0)º¯Êý¾ÍÖ´ÐУº
If the input field is empty, the function simply clears the content of the txtHint placeholder.
The stateChanged() function contains the following code:
stateChanged()º¯Êý°üº¬ÒÔÏ´úÂ룺
function stateChanged() |
The stateChanged() function executes every time the state of the XMLHTTP object changes.
ÿµ±XMLHTTP¶ÔÏóµÄ״̬·¢Éú¸Ä±ästateChanged()º¯Êý¾Í»á±»Ö´ÐÐ
When the state changes to 4 (or to "complete"), the content of the txtHint placeholder is filled with the response text.
µ±×´Ì¬¸Ä±äΪ4(»òΪ"Íê³É"),txtHint spanÀï¾Í»áÏÔʾ·´À¡µÄÎÄ×Ö