JavaScript parses AJAX-returned XML and JSON-formatted data

Source: Internet
Author: User

Write an example for later use

One, JavaScript parses the returned XML-formatted data:

1. JavaScript version of Ajax send request

(1), create XMLHttpRequest object, this object is the core of the AJAX request, is the AJAX request and response information carrier, only different browser creation method is different

(2), Request path

(3), using the open method binding to send the request

(4), send the request using the Send () method

(5), gets the string Xmlhttprequest.responsetext returned by the server;

(6), gets the value returned by the server, stores the xmlhttprequest.responsexml in the form of an XML object;

(7), the XML Document object is checked and parsed using the user's Dom node tree method and attributes.


2. Example:

(1), sending Ajax requests, and parsing the returned data


<script type= "Text/javascript" >
/* JS version to send AJAX requests */
function Tellxml () {
Create objects for Firefox and Safari
var xmlhttprequest= new XMLHttpRequest ();
Create object, suitable for IE
var xmlhttprequest=new activexobject ("msxml2.xmlhttp");
Request Send Path URL
var url= "http://localhost:18080/servlet/Servlet1?aa=10";
The Open method binds a send process, but does not send data. The Open method represents asynchronous when the last argument is true, otherwise the synchronization
Xmlhttprequest.open ("POST", url,true);
The Send method is the sending of the request data
Xmlhttprequest.send (URL);
ReadState is a property of a XMLHttpRequest object that records the state returned by the server
var readstate =xmlhttprequest.readystate;
Alert ("Status:" +readstate);
Status is the state of the sending request, and if it is 200, it indicates that the request responded successfully
var status=xmlhttprequest.status;
Alert ("Request send result" +status);
"ResponseText" is a property of XMLHttpRequest that stores the HTTP response value as a string, and the "Responsexml" property is a value that records the HTTP response in XML form.
var text= xmlhttprequest.responsetext;
alert (text);
"Responsexml" is a property of XMLHttpRequest that stores the value returned by the server side as an object of an XML document, and can be used to examine and parse the XML Document object using the user's Dom node tree method and properties.
var xml= xmlhttprequest.responsexml;
var values=xml.getelementsbytagname ("info");
Alert ("Value" +values);
Alert ("Length" +values.length);
Parse Get content
for (Var i=0;i<values.length;i++) {
var name1=values[i].getelementsbytagname ("name") [0].firstchild.data;
alert (NAME1);
}
};
</script>


(2), the servlet accepts the AJAX request:

@Override
protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
TODO auto-generated Method Stub
String aaa= request.getparameter ("AA");
System.out.print ("Ajax Data:" +AAA);
Responding to a message to a client
Response.setcharacterencoding ("GBK");
Response.setcontenttype ("Text/xml");
PrintWriter out= Response.getwriter ();
Out.print ("<?xml version=\" 1.0\ "encoding=\" Gbk\ "?>");
Out.println ("<infos>");
Out.println ("<info>");
Out.println ("<name>" + "name1" + "</name>");
Out.println ("<age>" +12+ "</age>");
Out.println ("<name>" + "name2" + "</name>");
Out.println ("<age>" +22+ "</age>");
Out.println ("</info>");
Out.println ("<info>");
Out.println ("<name>" + "Name11" + "</name>");
Out.println ("<age>" +112+ "</age>");
Out.println ("<name>" + "Name22" + "</name>");
Out.println ("<age>" +222+ "</age>");
Out.println ("</info>");
Out.println ("</infos>");

}



Second, JavaScript parses the returned JSON-formatted data: Note that this gets responsetext instead of Responsexml, which is the string instead of the XML object, because the JSON is returned

1. Send the request and parse the returned JSON-formatted data (this returns the format of the JSON object)
<script type= "Text/javascript" >
/* The format returned by JS Parsing is JSON */
function Telljson () {
Create a XMLHttpRequest Object
var xmlhttprequest= new XMLHttpRequest ();
Request URL
var url= "http://localhost:18080/servlet/Servlet3?aa=10";
Bind the request process to the Open method
Xmlhttprequest.open ("POST", url,true);

Send Request

Xmlhttprequest.send (URL);
ReadState is a property of a XMLHttpRequest object used to record the status of the server response
var readstate =xmlhttprequest.readystate;
Alert ("Request Readiness Status:" +readstate);

Status of server execution

var status=xmlhttprequest.status;
Alert ("Request send result" +status);
The ResponseText object is a property of the XMLHttpRequest object that is used to store the value returned by the server side as a string.
var text= xmlhttprequest.responsetext;
Alert ("JSON text:" +text);
Get JSON return value
Over there is a string in the format of the JSON object, which first converts the string to a JSON-formatted JS object in the foreground.
var json= eval ("(" +text+ ")");
Use the eval () method to convert a JSON-formatted string into a JS object and parse it to get the content
Alert ("Age:" +json.age+ "Age1:" +json.age1);

};
</script>


2. The servlet accepts the request and returns the data

protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Returning data in JSON format to Ajax
String aaa= request.getparameter ("AA");
System.out.print ("Ajax Data:" +AAA);
Responding to a message to a client
Response.setcharacterencoding ("GBK");
Response.setcontenttype ("Text/json");
PrintWriter out= Response.getwriter ();
This assembles the format of the JSON object and translates it back into a JSON-formatted string.
String stu= "{age:12,age1:23,age2:33}";

Out.print (Stu);
Out.flush ();
Out.close ();

}


Third, JavaScript parses the returned data in the JSON array format:

1. Send AJAX requests

<script type= "Text/javascript" >
/* The format returned by JS Parsing is JSON */
function Telljson () {
Create a XMLHttpRequest Object
var xmlhttprequest= new XMLHttpRequest ();
Request URL
var url= "http://localhost:18080/servlet/Servlet3?aa=10";
The Open method binds the request path
Xmlhttprequest.open ("POST", url,true);
Send an AJAX request

Xmlhttprequest.send (URL);
ReadState is a property of a XMLHttpRequest object used to record the status information returned by the server
var readstate =xmlhttprequest.readystate;
Alert ("Request Readiness Status:" +readstate);

The Status property is used to record the execution state information returned by the server

var status=xmlhttprequest.status;
Alert ("Request send result" +status);
The ResponseText property is used as a string to store the data returned by the server side
var text= xmlhttprequest.responsetext;
Alert ("JSON text:" +text);
That's the format of the JSON array, which converts the string of JSON array into a JS array via JS's eval () method.
var json= eval ("(" +text+ ")");
Parse this JS array to get the value

var age=json[0].age;
var age1=json[0].age1;
var age2=json[0].age2;
Alert ("Age:" +age+ "Age1" +age1+ "Age2" +age2);

};
</script>



Iv. three properties of the Ajax XMLHttpRequest object and the Open and send methods:

(1) onReadyStateChange Property
The onReadyStateChange property has functions that handle server responses. The following code defines an empty function that can be set at the same time as the onReadyStateChange property:

Xmlhttp.onreadystatechange=function ()
{
We need to write some code here.
}
(2) ReadyState property

The ReadyState property holds state information about the server response . The onreadystatechange function is executed whenever readyState changes.

This is the possible value of the ReadyState property:

Status description
0 The request was not initialized (before calling open ())
1 request has been made (before calling send ())
2 The request has been sent (here you can usually get the content header from the response)
3 in Request processing (usually some of the data in the response is available, but the server has not yet completed the response)
4 request completed (Can access server response and use it)

We want to add an if statement to this onreadystatechange function to test whether our response is complete (which means we can get the data):

Xmlhttp.onreadystatechange=function ()
{
if (xmlhttp.readystate==4)
{
Getting data from the server's response
}
}
(3) ResponseText property

The data returned by the server can be retrieved through the ResponseText property.

In our code, we will set the value of the time text box to equal to ResponseText:

Xmlhttp.onreadystatechange=function ()
{
if (xmlhttp.readystate==4)
{
Document.myform.time.value=xmlhttp.responsetext;
}
}

Other than that:

AJAX-Sending a request to the server
To send the request to the server, we need to use the open () method and the Send () method.

The open () method requires three parameters:

The first parameter defines the method (GET or POST) that is used to send the request.

GET is simpler and faster than POST, and can be used in most cases.

However, use the POST request in the following cases:

    • Unable to use cache file (update file or database on server)
    • Send a large amount of data to the server (POST has no data volume limit)
    • Post is more stable and more reliable than GET when sending user input with unknown characters

The second parameter specifies the URL of the server-side script , which can be any type of file, such as. txt and. xml, or server script files, such as. asp and. PHP (able to perform tasks on the server before the response is returned)).

The third parameter specifies that the request should be processed asynchronously(True (asynchronous) or False (synchronous)).

The Send () method can send the request to the server. If we assume that the HTML file and the ASP file are in the same directory, then the code is:

Xmlhttp.open ("GET", "time.asp", true);
Xmlhttp.send (NULL);


None of the previous instances use the onreadystatechange property of the XMLHttpRequest object, and look at an example of this attribute:1. onReadyStateChange This attribute is also stated in the previousXMLHttpRequest The readyState of this object will be executed when this value is changed.

2. Send Ajax request and parse

<script type= "Text/javascript" >
/* The format returned by JS Parsing is JSON */
function Telljson () {
Create objects for Firefox and Safari
var xmlhttprequest= new XMLHttpRequest ();
Request Send Path URL
var url= "http://localhost:18080/servlet/Servlet3?aa=10";
The Open method binds a send process, but does not send data. The Open method represents asynchronous when the last argument is true, otherwise the synchronization
Xmlhttprequest.open ("POST", url,true);
The Send method is the sending of the request data
Xmlhttprequest.send (URL);
The onReadyStateChange property has functions that handle server responses
Xmlhttprequest.onreadystatechange =function () {
The ReadyState property holds state information about the server response. The onreadystatechange function is executed whenever readyState changes.
Alert ("state changed:" +xmlhttprequest.readystate);
If the 4 request is complete (you can access the server response and use it)
if (xmlhttprequest.readystate==4) {
var readstate =xmlhttprequest.readystate;
Alert ("Request Readiness Status:" +readstate);
var status=xmlhttprequest.status;
Alert ("Request send result" +status);
"ResponseText" is a property of XMLHttpRequest that stores the HTTP response value as a string, and the "Responsexml" property is a value that records the HTTP response in XML form.
var text= xmlhttprequest.responsetext;
Alert ("JSON text:" +text);
Get JSON return value
This is the format of the JSON array, which is parsed as a JSON array.
var json= eval ("(" +text+ ")");
var age=json[0].age;
var age1=json[0].age1;
var age2=json[0].age2;
Alert ("Age:" +age+ "Age1" +age1+ "Age2" +age2);
}
}

};
</script>

3. Data returned by the servlet

protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException {
        //returns JSON-formatted data to Ajax
         String AAA = Request.getparameter ("AA");
        system.out.print ("Ajax Data:" + AAA);
        //response information to clients
         Response.setcharacterencoding ("GBK");
        response.setcontenttype ("Text/json");
        printwriter out = Response.getwriter ();
        //Use the format of the JSON array
        string stu = "[{ AGE:12,AGE1:23,AGE2:33}] ";
        out.print (STU);
        out.flush ();
        out.close ();
    }

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JavaScript parses AJAX-returned XML and JSON-formatted data

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.