My Ajax Study Notes

Source: Internet
Author: User
Tags xml file example

[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
  1. // Compatible with different browsers
  2. If (window. activexobject &&! Window. XMLHttpRequest)
  3. {
  4. Window. XMLHttpRequest = function ()
  5. {
  6. VaR MSXML = ['msxml2. xmlhttp.5.0 ',
  7. 'Msxml2. xmlhttp.4.0 ',
  8. 'Msxml2. xmlhttp.3.0 ',
  9. 'Msxml2. xmlhttp ',
  10. 'Microsoft. xmlhttp'];
  11. For (VAR I = 0; I <msxmls. length; I ++)
  12. {
  13. Try {
  14. Return new activexobject (msxmls [I]);
  15. } Catch (e ){}
  16. }
  17. Return NULL;
  18. };
  19. }
  20. VaR XMLHTTP = new XMLHttpRequest (); // create an XMLHTTPRequest object

Another method:

JavaScript code
  1. Function createxmlhttprequest ()
  2. {
  3. VaR XMLHTTP;
  4. Try {
  5. XMLHTTP = new XMLHttpRequest ();
  6. } Catch (e ){
  7. VaR MSXML = new array ("msxml2.xmlhttp. 6.0 ″,
  8. "Msxml2.xmlhttp. 5.0 ″,
  9. "Msxml2.xmlhttp. 4.0 ″,
  10. "Msxml2.xmlhttp. 3.0 ″,
  11. "Msxml2.xmlhttp ",
  12. "Microsof. XMLHTTP ");
  13. For (VAR I = 0; I <MSXML. Length &&! XMLHTTP; I ++)
  14. {
  15. Try {
  16. XMLHTTP = new activexobject (MSXML [I]);
  17. } Catch (e ){}
  18. }
  19. }
  20. If (! XMLHTTP)
  21. Alert ("ajax Error !");
  22. Else return XMLHTTP;
  23. }
  24. 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
  1. Function startajaxrequest (type)
  2. {
  3. Requesttype = type; // action type parameter
  4. XMLHTTP = new XMLHttpRequest (); // create an XMLHTTPRequest object
  5. XMLHTTP. onreadystatechange = handlestatechange;
  6. XMLHTTP. Open ("get", "http: // 127.0.0.1/diy_lib/XML/clients. xml", true );
  7. XMLHTTP. setRequestHeader ("If-modified-since", "0"); // disable caching
  8. XMLHTTP. Send (null );
  9. }
  10. Function handlestatechange ()
  11. {
  12. If (requesttype = "clear ")
  13. {
  14. Clearinfo ();
  15. } Else if (requesttype = "show ")
  16. {
  17. Showinfo ();
  18. }
  19. }
  20. Function clearinfo ()
  21. {
  22. Info. innerhtml = "";
  23. }
  24. Function showinfo ()
  25. {
  26. If (XMLHTTP. readystate = 4 & XMLHTTP. Status = 200)
  27. {
  28. Info. innerhtml = XMLHTTP. responsetext;
  29. }
  30. }

[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
  1. Function clearinfo ()
  2. {
  3. Document. getelementbyid ('info'). innerhtml = "";
  4. }
  5. Function showinfo ()
  6. {
  7. If (XMLHTTP. readystate = 4 & XMLHTTP. Status = 200)
  8. {
  9. Document. getelementbyid ('info'). innerhtml = XMLHTTP. responsetext;
  10. }
  11. }

Use the responsexml method to process XML response information:
XML file example

XML/html code
  1. <Datetime>
  2. <Date>
  3. <State> 2008-1-1 </State>
  4. <State> 2008-2-2 </State>
  5. </Date>
  6. <Time>
  7. <State> 11:11:11 </State>
  8. <State> 22:22:22 </State>
  9. </Time>
  10. </Datetime>

Methods for returning XML documents on the PHP page:
Header ("Content-Type: Application/XML ");

Reading some Dom code in JS

JavaScript code
  1. VaR xmldoc = XMLHTTP. responsexml;
  2. VaR userdoc = xmldoc. getelementsbytagname ('datetime') [0];
  3. VaR DATA = userdoc. getelementsbytagname ('date') [0];
  4. VaR data1 = userdoc. getelementsbytagname ('time') [0];
  5. VaR info_date = data. getelementsbytagname ('state') [0]. childnodes [0]. nodevalue;
  6. 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
  1. VaR info_date = data. getelementsbytagname ('state') [1]. childnodes [0]. nodevalue;
  2. 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
  1. Function addtablerow (date, time) // Add a new row
  2. {
  3. VaR ROW = Document. createelement ("TR"); // creates the tr element and returns the row object.
  4. VaR cell = createcellwithtext (date); // call the function to create a text
  5. Row. appendchild (cell); // Add text to the row object
  6. Cell = createcellwithtext (time );
  7. Row. appendchild (cell );
  8. Document. getelementbyid ("Table1"). appendchild (ROW); // Add the row object to the specified element.
  9. }
  10. Function createcellwithtext (text) // create text content
  11. {
  12. VaR cell = Document. createelement ("TD"); // creates a TD element and returns the cell object.
  13. VaR textnode = Document. createtextnode (text); // create a text node
  14. Cell. appendchild (textnode); // Add to Cell Object
  15. Return cell;
  16. }

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
  1. VaR flag = Document. createelement (FLAG); // create a format label
  2. Flag. setattribute ('align ', 'center'); // set tag attributes
  3. 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
  1. VaR Company =
  2. {"Employees ":[
  3. {"Firstname": "Brett", "lastname": "McLaughlin", "email": brett@newInstance.com "},
  4. {"Firstname": "Jason", "lastname": "Hunter", "email": "jason@servlets.com "},
  5. {"Firstname": "elliotte", "lastname": "Harold", "email": "elharo@macfaq.com "}
  6. ]
  7. };

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
  1. VaR requestobj = new XMLHttpRequest ();
  2. VaR newdata = "name = linvo & Pwd = 123 ″;
  3. Requestobj. Open ("Post", "do. php", true );
  4. Requestobj. setRequestHeader ('content-type', 'application/X-WWW-form-urlencoded; charset = UTF-8 ′);
  5. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.