[Date]
======================================
Ajax request/response mode
0. Ajax event triggering
1. Create an XMLHTTPRequest object
2. open () method: Create a server call
3. Specify an event handler for onreadystatechange
4. Send () method: send a request to the server (CGI program)
5. (The request is returned to the browser)
6. Response to event processing functions
---------
Create an XMLHTTPRequest object
JavaScript code
- // Compatible with different browsers
- If (window. activexobject &&! Window. XMLHttpRequest)
- {
- Window. XMLHttpRequest = function ()
- {
- VaR MSXML = ['msxml2. xmlhttp.5.0 ',
- 'Msxml2. xmlhttp.4.0 ',
- 'Msxml2. xmlhttp.3.0 ',
- 'Msxml2. xmlhttp ',
- 'Microsoft. xmlhttp'];
- For (VAR I = 0; I <msxmls. length; I ++)
- {
- Try {
- Return new activexobject (msxmls [I]);
- } Catch (e ){}
- }
- Return NULL;
- };
- }
- VaR XMLHTTP = new XMLHttpRequest (); // create an XMLHTTPRequest object
Another method:
JavaScript code
- Function createxmlhttprequest ()
- {
- VaR XMLHTTP;
- Try {
- XMLHTTP = new XMLHttpRequest ();
- } Catch (e ){
- VaR MSXML = new array ("msxml2.xmlhttp. 6.0 ″,
- "Msxml2.xmlhttp. 5.0 ″,
- "Msxml2.xmlhttp. 4.0 ″,
- "Msxml2.xmlhttp. 3.0 ″,
- "Msxml2.xmlhttp ",
- "Microsof. XMLHTTP ");
- For (VAR I = 0; I <MSXML. Length &&! XMLHTTP; I ++)
- {
- Try {
- XMLHTTP = new activexobject (MSXML [I]);
- } Catch (e ){}
- }
- }
- If (! XMLHTTP)
- Alert ("ajax Error !");
- Else return XMLHTTP;
- }
- VaR XMLHTTP = new createxmlhttprequest (); // create an XMLHTTPRequest object
-------------------
Open () method
Open ("method", "url", bool)
For example, XMLHTTP. Open ("get", "http: // 127.0.0.1/clients. xml", true );
----------------------
XMLHttpRequest attributes:
Onreadystatechange
This event processor is triggered when each state changes. A JavaScript function is usually called.
......................................................................................................
Readystate
Request status. Five optional values: 0 = not initialized, 1 = loading, 2 = loaded, 3 = interaction, 4 = completed
......................................................................................................
Responsetext
Server Response, expressed as a string
......................................................................................................
Responsexml
Server Response, which is expressed as XML. This object can be parsed as a DOM object.
......................................................................................................
Status
HTTP status code of the server (200 corresponds to OK, 404 corresponds to not found (not found), and so on)
......................................................................................................
Statustext
The corresponding text of the HTTP status code (OK or not found (not found) and so on)
......................................................................................................
[Date]
======================================
Some content is written as function implementation:
JavaScript code
- Function startajaxrequest (type)
- {
- Requesttype = type; // action type parameter
- XMLHTTP = new XMLHttpRequest (); // create an XMLHTTPRequest object
- XMLHTTP. onreadystatechange = handlestatechange;
- XMLHTTP. Open ("get", "http: // 127.0.0.1/diy_lib/XML/clients. xml", true );
- XMLHTTP. setRequestHeader ("If-modified-since", "0"); // disable caching
- XMLHTTP. Send (null );
- }
- Function handlestatechange ()
- {
- If (requesttype = "clear ")
- {
- Clearinfo ();
- } Else if (requesttype = "show ")
- {
- Showinfo ();
- }
- }
- Function clearinfo ()
- {
- Info. innerhtml = "";
- }
- Function showinfo ()
- {
- If (XMLHTTP. readystate = 4 & XMLHTTP. Status = 200)
- {
- Info. innerhtml = XMLHTTP. responsetext;
- }
- }
[Date]
======================================
Operate dom (1 ):
Document. getelementbyid ('html _ id ')
Returns the Element Object Whose tag ID is html_id in HTML.
Rewrite the above two functions according to W3C standards
JavaScript code
- Function clearinfo ()
- {
- Document. getelementbyid ('info'). innerhtml = "";
- }
- Function showinfo ()
- {
- If (XMLHTTP. readystate = 4 & XMLHTTP. Status = 200)
- {
- Document. getelementbyid ('info'). innerhtml = XMLHTTP. responsetext;
- }
- }
Use the responsexml method to process XML response information:
XML file example
XML/html code
- <Datetime>
- <Date>
- <State> 2008-1-1 </State>
- <State> 2008-2-2 </State>
- </Date>
- <Time>
- <State> 11:11:11 </State>
- <State> 22:22:22 </State>
- </Time>
- </Datetime>
Methods for returning XML documents on the PHP page:
Header ("Content-Type: Application/XML ");
Reading some Dom code in JS
JavaScript code
- VaR xmldoc = XMLHTTP. responsexml;
- VaR userdoc = xmldoc. getelementsbytagname ('datetime') [0];
- VaR DATA = userdoc. getelementsbytagname ('date') [0];
- VaR data1 = userdoc. getelementsbytagname ('time') [0];
- VaR info_date = data. getelementsbytagname ('state') [0]. childnodes [0]. nodevalue;
- VaR info_time = data1.getelementsbytagname ('state') [0]. childnodes [0]. nodevalue;
Result:
Info_date: 2008-1-1
Info_time: 11:11:11
Modify the last two rows
JavaScript code
- VaR info_date = data. getelementsbytagname ('state') [1]. childnodes [0]. nodevalue;
- VaR info_time = data1.getelementsbytagname ('state') [1]. childnodes [0]. nodevalue;
Result:
Info_date: 2008-2-2
Info_time: 22:22:22
[Date]
======================================
Operate dom (2 ):
Add Table content
Two new functions
JavaScript code
- Function addtablerow (date, time) // Add a new row
- {
- VaR ROW = Document. createelement ("TR"); // creates the tr element and returns the row object.
-
- VaR cell = createcellwithtext (date); // call the function to create a text
- Row. appendchild (cell); // Add text to the row object
- Cell = createcellwithtext (time );
- Row. appendchild (cell );
-
- Document. getelementbyid ("Table1"). appendchild (ROW); // Add the row object to the specified element.
- }
-
- Function createcellwithtext (text) // create text content
- {
- VaR cell = Document. createelement ("TD"); // creates a TD element and returns the cell object.
- VaR textnode = Document. createtextnode (text); // create a text node
- Cell. appendchild (textnode); // Add to Cell Object
- Return cell;
- }
Call method:
Addtablerow (info_date, info_time );
Note: tbody labels must be used for tables in HTML.
Example:
<Table>
<Tbody id = "Table1">
</Tbody>
</Table>
[Date]
======================================
Operate dom (3 ):
Integrated instance application
See project card source code
Note:
Document. getelementbytagname () Return Value Type: array ---------------
Create formatted text content
JavaScript code
- VaR flag = Document. createelement (FLAG); // create a format label
- Flag. setattribute ('align ', 'center'); // set tag attributes
- Flag. innerhtml = text; // content after the tag
If the PHP file that generates XML contains Chinese characters, it needs to be saved in UTF-8 format
[Date]
======================================
JSON application:
Assign JSON data to a variable (for example ):
JavaScript code
- VaR Company =
- {"Employees ":[
- {"Firstname": "Brett", "lastname": "McLaughlin", "email": brett@newInstance.com "},
- {"Firstname": "Jason", "lastname": "Hunter", "email": "jason@servlets.com "},
- {"Firstname": "elliotte", "lastname": "Harold", "email": "elharo@macfaq.com "}
- ]
- };
Obtain the firstname information of the first employee: Company. Employees [0]. fristname
---------------------
JSON receiving (example)
1. The server returns the corresponding JSON text Representation
{"City": "Hefei", "Province": "Anhui "}
2. Use the eval () function to convert JSON text into JavaScript objects.
VaR response = eval ("(" + XMLHTTP. responsetext + ")");
Note: The extra parentheses enable the eval () function to parse the source input unconditionally as an expression.
3. Get the corresponding value from the object
Response. City
Response. Province
[Q &]
======================================
Q1: Get or post?
A1: Use the POST method (for example)
JavaScript code
- VaR requestobj = new XMLHttpRequest ();
- VaR newdata = "name = linvo & Pwd = 123 ″;
- Requestobj. Open ("Post", "do. php", true );
- Requestobj. setRequestHeader ('content-type', 'application/X-WWW-form-urlencoded; charset = UTF-8 ′);
- Requestobj. Send (newdata );
Q2: After modifying the content of the XML file, why does Ajax still display the original content?
A2: XMLHTTP. setRequestHeader ("If-modified-since", "0"); // disable caching