Ajax and JSON combat

Source: Internet
Author: User


Directory: (Ctrl+f for retrieval)
The method and instance of the underlying AJAX asynchronous request background operation in 1.javascript.
2.jquery how to work with Ajax
3.ajax explanation
4.json explanation
The processing of JSON in 5.java.
6.java values the JSON data to the foreground.
JSON is processed by the 7.jsp foreground.
8.ajax asynchronously gets the JSON in the background and processes it.
--------------------------------------------
1. Traditional Ajax method of asynchronous request background operation.
Features: Local refresh, asynchronous interaction.
Introduction of Javascript.js:
<script type= "Text/javascript" src= "Http://libs.cdnjs.net/jquery/3.2.1/jquery.js" ></script>
This is the front-end public library CDN Accelerated Remote Warehouse, of course, can also download the relevant JS file and then introduced, but must be more than 1.4 version. The previous versions were almost useless.

The traditional notation:

1<script type= "Text/javascript" >2function Createxmlhttprequest () {//to handle all modern browsers, including IE5 and IE6, check whether the browser supports XMLHttpRequest objects. 3         //if supported, the XMLHttpRequest object is created. If not supported, create the ActiveXObject:4         //The first step is to create the XMLHttpRequest ()5         Try {6XmlHttp =NewXMLHttpRequest ();7}Catch(tryms) {8             Try {9XmlHttp =NewActiveXObject ("Msxml2.xmlhttp");Ten}Catch(otherms) { One                 Try { AXmlHttp =NewActiveXObject ("Microsoft.XMLHTTP"); -}Catch(failed) { -XmlHttp =NULL; the                     //Here you can report an error, unable to get the XMLHttpRequest object -                 } -             } -         } +         returnxmlHttp; -     } +Window.onload =function () { Adocument.getElementById ("B1"). onclick =function () { at             //calling Ajax to send a request -             /** - * 1. Create a XMLHttpRequest object - * 2. Binding callback function - * 3. Establish a connection to the server - * 4. Send data in * 5. The callback function handles the corresponding data -              */ to             //First step: Create a XMLHttpRequest object and look up how to verify the browser support ↑ +var xmlHttp =createxmlhttprequest (); -  the             //Step Two: Bind the callback function *  $Xmlhttp.onreadystatechange =function () {Panax Notoginseng                 if(Xmlhttp.readystate = = 4) { -                     //indicates that the status of ReadyState is already in the fourth step, the data is received, at this time through the responsebody and responsetext to obtain the complete response data, the                     //See This article for an explanation of the five states of Ajax readystate:http://www.jb51.net/article/16966.htm +                     if(Xmlhttp.status = = 200) {//an HTTP status code of 200 indicates normal interaction completion.  A                         //You can set the callback function if both steps have been verified. thevar callback =Xmlhttp.responsetext; +                         //to obtain a response from the server, use the ResponseText or Responsexml property of the XMLHttpRequest object.  -                         //ResponseText is the response data that gets the form of a string. The Responsexml receives the response data in XML form.  $document.getElementById ("Mydiv"). InnerHTML = callback;//This allows the callback function to be processed by default. Here, for example, the callback function is shown in the tag with ID mydiv.  $                     } -                 } -             } the             //Step Three: Establish a connection to the server -Xmlhttp.open ("POST", ".. /servlet/ajaxservlet ",true);Wuyi             //The first parameter is the requested type, get or post, but get will get the cached data, get the amount of data to carry limited, get to a large number of unknown character input instability, when there are three points above the barrier, please select Post; the             //The second parameter is the requested address URL, which can request any type of file, such as. txt. xml or. js, to prevent virtual path problems, we recommend that you dynamically obtain the address using El Expression and modify the URL to: "${ Pagecontext.request.contextpath}/servlet/ajaxservlet ". Furthermore, if you are worried about getting requests for cached data, you can make the address different every time you get a cache, such as this: "${pagecontext.request.contextpath}/servlet/ajaxservlet?" T= "+math.random ().  -             //The third parameter is to set the async parameter, which is true for an asynchronous request, false for a synchronous request, false for a request that causes the browser to lock, and so that the data is processed before the page can be manipulated. Also, when you use Async=false, do not write the onreadystatechange function, put the code behind the Send () statement. That is, the document.getElementById ("Mydiv"). Innerhtml=callback; Put the paragraph behind the send.  Wu             //Fourth Step: Send a request to the server -Xmlhttp.setrequestheader ("Content-type", About"application/x-www-form-urlencoded");//adds an HTTP header to the request. You can add more than one. Self-Baidu.  $Xmlhttp.send ("Name= Zhang San");//The string in send is in the request body and is used only at post, and the get is empty because the example is the data for the POST request, so here is an example.  -         } -     } -</script>

The underlying AJAX case:
1. The underlying Ajax gets a. txt file with Get
The TXT file is placed in the Webroot folder, and the. txt content is:

1 <p id= "txt1" style= "color:red" >woshi Yiduan txt wenben!</p>2 <p id= "Txt2" >woshi Dier Duan Txt Wenben!</p>

JS Code:

  

1<script type= "Text/javascript" >2 function Createxmlhttprequest () {3         Try {4XmlHttp =NewXMLHttpRequest ();5}Catch(tryms) {6             Try {7XmlHttp =NewActiveXObject ("Msxml2.xmlhttp");8}Catch(otherms) {9                 Try {TenXmlHttp =NewActiveXObject ("Microsoft.XMLHTTP"); One}Catch(failed) { AXmlHttp =NULL; -                     //Here you can report an error, unable to get the XMLHttpRequest object -                 } the             } -         } -         returnxmlHttp; -     } +Window.onload =function () { -document.getElementById ("Bt1"). onclick =function () { +var xmlHttp =createxmlhttprequest (); AXmlhttp.onreadystatechange =function () { at                 if(Xmlhttp.readystate = = 4 && xmlhttp.status = 200) { -document.getElementById ("Mydiv"). InnerHTML =Xmlhttp.responsetext; -                 } -             } -  -Xmlhttp.open ("GET", in"${pagecontext.request.contextpath}/test/test.txt?t=" -+ Math.random (),true); to  +Xmlhttp.setrequestheader ("Content-type", -"Application/x-www-form-urlencoded"); the xmlhttp.send (); *         } $     }Panax Notoginseng</script> -  the  + A  the<body> +  -<div id= "Mydiv" > $ $</div> -<button id= "BT1" > Change content </button> -  the</body>

Show Results:

  

Description: How can there be color change here? Because, our xmlhttp.responsetext can automatically convert the label,




---------------------------------
2.json
Description: JSON is a form of data interaction.
Interactive format for data:
1.xml
1. When the label appears in pairs
The format in 2.xml is fixed in pairs and is not allowed to be modified.
If the data requirements are more stringent, the preferred XML (message)
2.JSON
1.JSON is a lightweight form of data interaction.
During the transfer process, only valid information needs to be passed.
For data requirements are relatively loose, and delivery speed is faster.
JSON format Description:
Array format:
["Value1", "value2", "Value3"]

Object Format:
{"id": "1", "Name": "Tom"}

Complex format:
a:["value1", "value2", {"id": 1, "name": "Tom"}]
B:[{id: "1", Name: "Tom"},{id:2,name: "Jerry"},{id:3,name: "Herry"}]
Syntax: If the value is a number. Can not add "" number, if the value is a character, you must add "", for Key, (note is key! is the object format! ), plus no "" is OK.
The above JSON format to keep in mind! Remember! Remember! The important thing to say three times. I can't remember, just add the quotes!
-------------------------
3.java different ways to relay JSON
The first: string type, to write a string in JSON format, as above.
such as: String str = {"Book1": [{"Yema": "1", "Neirong": "Genteel"},{"page number": "$", "Neirong": "Knight Fragment"}], "Book2": [{"Page number": "[{"] "", "Content": " Love fragment "},{" page ":" 5 "," Neirong ":" Horror Fragment "}]};
But! It is not possible to write this directly in Java, because "" will compile the error, need to be escaped with the \ number to each "number, there is a website can be quickly escaped, address, http://www.sojson.com/yasuo.html
After escaping, it's like this.
String str = "{\" book1\ ": [{\" yema\ ": \" 12\ ", \" neirong\ ": \" genteel \ "},{\" page number \ ": \" 22\ ", \" neirong\ ": \" Knight fragment \ "}],\" book2\ ": [{ \ "page number \": \ "1\", \ "content \": \ "Love fragment \"},{\ "page number \": \ "5\", \ "neirong\": \ "horror fragment \"}]} ";
See. This section is in Java and there is no problem.

Ajax and JSON combat

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.