Ajax development Framework and applications for XMLHttpRequest, ResponseText, Responsexml, and JSON

Source: Internet
Author: User

1 AJAX Development Framework

2 A Initialize the XMLHttpRequest object

3 b Specifies the response handler function

4 C make an HTTP request

5 D processing the information returned by the server

6 Data Format Feed

6 advantages

6 Disadvantages

7 parsing JSON

Ajax Development Framework

Ajax essentially follows the request/server pattern, so the basic process of this framework is:

Object initialization

Send Request

server receives

Server returns

Client receives

Modify the contents of the client page.

It's just that the process is asynchronous.

A initializes the XMLHttpRequest object

function Createxmlhttprequest () {

var xmlHttp;

try{//firefox, Opera 8.0+, Safari

Xmlhttp=new XMLHttpRequest ();

}catch (e) {

try{//internet Explorer

Xmlhttp=new ActiveXObject ("msxml2.xmlhttp");

}catch (e) {

try{

Xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP");

}catch (e) {}

}

}

return xmlHttp;

B. Specify the response handler function

Specifies how the client handles when the server returns information. As long as the corresponding handler function name is assigned to the onReadyStateChange property of the XMLHttpRequest object. For example:

Xmlhttpreq.onreadystatechange = ProcessResponse;

Note: This function name is not enclosed in parentheses, and no parameters are specified. You can also use JavaScript functions to define response functions in a direct way. Like what:

Xmlhttpreq.onreadystatechange = function () {};

function to process return information

function ProcessResponse () {

}

C. Make an HTTP request

An HTTP request was made to the server. This step calls the open and send methods of the XMLHttpRequest object.

Http_request.open (' GET ', ' http://www.example.org/some.file ', true);

Http_request.send (NULL)

In order, the Send method is called after the open call is complete. The send parameter can be any content that you want to pass to the server if it is sent by post.

Note: If you want to pass files or post content to the server, you must first call the setRequestHeader method to modify the MIME category. As follows:

Http_request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");

The data is listed in the form of a query string as a parameter to send, for example:

Name=value&anothername=othervalue&so=on

Code

Send Request

function SendRequest () {

Get the value of a text box

var Chatmsg=input.value;

var url= "chatservlet.do?charmsg=" +CHATMSG;

Make a call to the server

Xmlhttpreq.open ("POST", url,true);

Sets the MIME category, if you send data to the server with a POST request,

The header of "content-type" needs to be set to "application/x-www-form-urlencoded".

It tells the server that the data is being sent, and that the data is already URL-encoded.

Xmlhttpreq.setrequestheader ("Content-type", "application/x-www-form-urlencoded");

The state changes the event trigger, the state change of the client will trigger the ReadyStateChange event,

onReadyStateChange will invoke the appropriate event handler function

Xmlhttpreq.onreadystatechange=processresponse;

Send data

Xmlhttpreq.send (NULL);

}

Send Request

function SendRequest () {

Get the value of a text box

var Chatmsg=input.value;

var url= "chatservlet.do?charmsg=" +CHATMSG;

Make a call to the server

Xmlhttpreq.open ("POST", url,true);

Sets the MIME category, if you send data to the server with a POST request,

The header of "content-type" needs to be set to "application/x-www-form-urlencoded".

It tells the server that the data is being sent, and that the data is already URL-encoded.

Xmlhttpreq.setrequestheader ("Content-type", "application/x-www-form-urlencoded");

The state changes the event trigger, the state change of the client will trigger the ReadyStateChange event,

onReadyStateChange will invoke the appropriate event handler function

Xmlhttpreq.onreadystatechange=processresponse;

Send data

Xmlhttpreq.send (NULL);

}

What to do with the response handler function.

First, it checks the readystate value of the XMLHttpRequest object to determine the current state of the request. Referring to the previous attribute table, you can know that the readystate value is 4, the server has returned all the information, you can start processing information and update the page content. As follows:

if (http_request.readystate = = 4) {

Information has been returned and can begin processing

} else {

Information has not returned, wait

}

After the server returns information, it also needs to determine the HTTP status code returned, to determine that the returned page has no errors. All status codes can be found on the official website of the Web site. Of these, 200 represents a normal page.

if (Http_request.status = = 200) {

The page is working and you can start processing information

} else {

Page has a problem

}

D. Processing the information returned by the server

XMLHttpRequest has two ways of handling information that is successfully returned:

ResponseText: The returned information is used as a string;

Responsexml: The information returned is used in the XML document and can be processed in the DOM.

Code

function to process return information

function ProcessResponse () {

if (xmlhttpreq.readystate==4) {//Judgment Object Status 4 means complete

if (xmlhttpreq.status==200) {//information has been successfully returned to start processing information

document.getElementById ("Chatarea"). Value=xmlhttpreq.responsetext;

}

}

}

Data format Feed

On the server side Ajax is a language-independent technology. What server-side languages are used at the business logic level.

When receiving data from the server side, those data must be sent in a format that the browser can understand. The server-side programming language can only return data in the following 3 formats:

Xml

Json

Html

Xml

Advantages:

XML is a common data format.

Instead of forcing data into a defined format, you want to customize the appropriate markup for your data.

The DOM gives you complete control over the document.

Disadvantages:

If the document comes from a server, you must ensure that the document contains the correct header information. If the document type is incorrect, then the value of Responsexml will be empty.

Dom parsing can be complicated when a long XML file is received by the browser

Json

JSON (JavaScript Object Notation) is a simple data format that is lighter than XML. JSON is a native JavaScript format, which means that working with JSON data in JavaScript does not require any special APIs or toolkits.

The rules of JSON are simple: an object is an unordered collection of "name/value pairs". An object starts with "{" (opening parenthesis) and "}" (the closing parenthesis) ends. Each "name" is followed by a ":" (colon); "' Name/value ' pair ' is separated by", "(comma).

The rules are as follows:

1) The map is represented by a colon (":"). Name: Value

2) The data is separated by commas (","). Name 1: value 1, Name 2: Value 2

3) The set of Mappings (objects) are represented by curly braces ("{}"). {Name 1: value 1, Name 2: Value 2}

4) a set (array) of side data is expressed in square brackets ("[]").

[

{Name 1: value, Name 2: Value 2},

{Name 1: value, Name 2: Value 2}

]

5 The type that the element value can have: string, number, object, array, True, false, NULL

JSON sample

Parsing JSON

JSON assigns a value with a colon (not an equal sign). Each assignment statement is separated by commas. The entire object is enclosed in curly braces. You can use curly braces to rank nested data.

The data stored in the object description can be a string, a number, or a Boolean value. Object descriptions can also store functions, which are methods of objects.

JSON is just a text string. It is stored in the ResponseText property

In order to read the JSON data stored in the ResponseText attribute, you need to base the Eval statement on JavaScript. The function eval treats a string as its argument. The string is then executed as JavaScript code. Because the JSON string is made up of JavaScript code, it's inherently executable.

code example:

JS processing JSON

Example one:

<script language= "JavaScript" >

var people ={"FirstName": "Brett", "LastName": "McLaughlin",

"Email": "[email protected]"};

alert (people.firstname);

alert (people.lastname);

alert (People.email);

</script>

Example two:

<script language= "JavaScript" >

var people =[

{"FirstName": "Brett", "email": "[email protected]"},

{"FirstName": "Mary", "email": "[email protected]"}

];

alert (people[0].firstname);

alert (People[0].email);

alert (people[1].firstname);

alert (People[1].email);

</script>

Example three:

<script language= "JavaScript" >

var people ={

"Programmers":

[

{"FirstName": "Brett", "email": "[email protected]"},

{"FirstName": "Jason", "email": "[email protected]"}

]

};

Window.alert (People.programmers[0].firstname);

Window.alert (People.programmers[1].email);

</script>

Example four:

<script language= "JavaScript" >

var people ={

"Programmers": [

{"FirstName": "Brett", "email": "[email protected]"},

{"FirstName": "Jason", "email": "[email protected]"},

{"FirstName": "Elliotte", "LastName": "Harold", "email": "[email protected]"}

],

"Authors": [

{"FirstName": "Isaac", "Genre": "Science Fiction"},

{"FirstName": "Tad", "Genre": "Fantasy"},

{"FirstName": "Frank", "Genre": "Christian Fiction"}

],

"Musicians": [

{"FirstName": "Eric", "instrument": "Guitar"},

{"FirstName": "Sergei", "Instrument": "Piano"}

]};

Window.alert (People.programmers[1].firstname);

Window.alert (people.musicians[1].instrument);

</script>

Example Five

<script language= "JavaScript" >

var people ={

"username": "Mary",

"Age": "20",

"Info": {"tel": "1234566", "Celltelphone": 788666},

"Address": [

{"City": "Beijing", "code": "1000022"},

{"City": "Shanghai", "Code": "2210444"}

]

};

Window.alert (People.username);

Window.alert (People.info.tel);

Window.alert (people.address[0].city);

</script>

JSON summary

Advantages:

As a data transfer format, JSON is similar to XML, but it is more dexterous.

JSON does not need to send header information that contains a specific content type from the server side.

Disadvantages:

The grammar is too rigorous

Code is hard to read

There is a risk to the Eval function

Parsing HTML

HTML is made up of some plain text. If the server sends HTML through XMLHttpRequest, the text is stored in the ResponseText property.

You do not have to read the data from the ResponseText property. It is already in the desired format and can be inserted directly into the page.

The simplest way to insert HTML code is to update the innerHTML property of this element.

HTML Summary

Advantages:

HTML code sent from the server side does not need to be parsed by JavaScript on the browser side.

HTML is good readability.

The HTML code block is more efficient than the innerHTML attribute.

Disadvantages:

HTML is inappropriate if you need to update multiple parts of a document via Ajax

innerHTML is not a DOM standard.

Comparison summary

When an application does not need to share data with other applications, the simplest use of HTML fragments to return data

If the data needs to be reused, the JSON file is a good choice, with advantages in terms of performance and file size

XML documents are preferred when the remote application is unknown, because XML is the "Esperanto" of the Web services domain

http://blog.csdn.net/chuyuqing/article/details/8687614

Ajax development Framework and applications for XMLHttpRequest, ResponseText, Responsexml, and JSON

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.