Ajax, Ajax coding problems

Source: Internet
Author: User
Tags response code

1. AJAX

1.1. AJAX Principles

1.1.1. issues with registration

When users use a BS-structured program, they often encounter issues like the 1:

Figure-1

After the user fills in the information, sends the request to the server, after clicking sends, the client browser will destroy the current page to wait for the response corresponding to the request, and then load the page that the response returns. But often the information sent to the Web server, some data is to be validated for validation, such as checking whether the user name is duplicated, once this information is not used after inspection, then the Web server returned the full page is not what the user expects to see the page, perhaps just a simple error message description, so, The user has to fill in the legal information again and the information that has not been verified, waiting for the server to verify again.

In this process, the user fills in a lot of information, the result because the validation failed and had to fill out the form data again, interrupted the user's operation.

If the user's information can not be passed after repeated verification, then this period not only consumes the network resources, but also occupies the resources of the server, reducing the server's amount of efficiency.

So in order to better enhance the user experience, and improve the efficiency of the server, reduce the network unnecessary data transfer, Ajax technology from the IE5 began to be accepted, not only to enhance the user's experience, but also improve the efficiency of the server side.

1.1.2. What is Ajax

Asynchronous JavaScript and XML (asynchronous JavaScript and XML)

Ajax is a technology to improve the user experience, the essence is to use the XMLHttpRequest object asynchronously to the server request, and send the request at the same time the browser does not destroy the page, you can continue the operation of the page, after the server receives the request will return some data, rather than a full page. When the browser receives these portions of the data, it changes the local content in the page with the effect of no refresh on the page.

The whole process has a multi-threaded feel, the page can now continue to operate, and behind the secretly like the server sent a request, but the client will not have any awareness, will not interrupt the operation of the client. For the server, the amount of data received is small, the amount of data returned is also small, very high efficiency, reduce unnecessary data transmission and judgment.

1.1.3. How AJAX works

The Ajxa works as shown in Figure –2:

Figure-2

An Ajax object is added to the browser that is responsible for sending the request, and the object is bound to an event handler in advance. When the user fills in the information by clicking on the registration, it calls the Ajax object's method, lets it send the request, the Ajax object sends the request does not affect the existence of the page, so in the Ajax object send the request colleague, the form page can continue the other work. When the server receives the request and obtains the data, it is judged that the data in response is no longer a complete page, but part of the data. When some of the data provided by the response arrives at the client, it is not displayed directly by the browser, but is received and parsed by the event handler that is ready for implementation. After the partial data is taken out, the JavaScript code controls the data and style, and then updates to a location on the page.

Throughout the process, Ajax is responsible for sending requests, accepting the responses returned, and updating the data in the response to the page.

1.1.4. How to get Ajax objects

Use the following code to get to an Ajax object:

function  getxhr () {        null;         if (window. XMLHttpRequest) {            xhr  new  XMLHttpRequest ();        } Else {            new activexobject (' Microsoft. XMLHTTP ');        }         return xhr;}

The Ajax object itself is an object in the browser, but it behaves as an ActiveX in IE. So when you create the object in the JavaScript language, you need to distinguish between different browsers.

After judging the window. XMLHttpRequest is present, the XMLHttpRequest object of this core is directly new. If this object does not exist, it could be IE browser, so create a ActiveXObject object.

Creating this XMLHttpRequest object is the basis for subsequent operations, and it is the existence of this object that makes the asynchronous request possible.

1.2. AJAX Object Properties and Methods

1.2.1. Properties and methods for asynchronous objects

Sometimes we call the XMLHttpRequest object an Ajax object, or an asynchronous object. Its properties and methods are shown in table 1

Table -1 Properties and methods of Ajax objects

1.2.2. onreadystatechange

onReadyStateChange needs to bind an event handler function to handle the ReadyStateChange event. The event is set by the system when the value of the readystate of the Ajax object has changed. For example, from 0 to 1, a ReadyStateChange event is generated. In the current different processing state, can carry on the state capture, do some corresponding processing. Each time the state changes will trigger the onReadyStateChange binding handler function, but most of the time we only need to know from 3 to 4, that is, the current readystate is 4 o'clock this state, the data response has been returned, and received success, waiting for the next step of processing. Most of the formats are as follows:

Xhr.onreadystatechange=function () {

... ...

Processing the returned data

}

1.2.3. readyState

ReadyState represents the state of the request, using a different number to represent a state.

    • 0 represents not yet initialized
    • 1 indicates a request is being sent
    • 2 on behalf of request completion
    • 3 Rep request succeeded, receiving data
    • 4 indicates successful data reception

Changes in the state of the number from 0 to 1 to 2 in order to determine the number of different states can provide more accurate processing. The most important thing is to judge the state of 4, which is the final state, which can parse the data and display it in the page.

The format of the writing code for the state's judgment is as follows:

xhr.onreadystatechange=function () {if(xhr.readystate = = 4)    {= xhr.responsetext;      // Show data to page         }    }

However, the State does not guarantee that the returned data is the data we want, or it may be the error message sent back. So to ensure that the received data is a successful response to the data, but also to add another attribute of the judgment--status. This property code responds with the status code, 200 for success, 404 for No Resource found, and 500 for the server that has a running exception.

The following code is a logical judgment structure that typically uses Ajax:

function Check_username () {//Get Ajax Objectsvar xhr=getxhr (); //Send Requestvar uri= ' check_username.do?username= ' + $F (' username ')); Xhr.open (' Get ', encodeURI (URI),true); Xhr.onreadystatechange=function () {/*only XHR's readystate equals 4 o'clock, HR obtains all the data returned by the server. */                if(Xhr.readystate = = 4 && xhr.status = 200){                     //correct datavar txt=Xhr.responsetext; $(' Username_msg '). InnerHTML =txt; }Else{                     //An error has occurred                     $(' Username_msg '). InnerHTML = ' Error validating user name ';        }        }; $(' Username_msg '). InnerHTML = ' checking ... '; Xhr.send (NULL); }

1.3. AJAX Programming Implementation

1.3.1. getting Ajax objects

When using code to get an Ajax object, the code is more and encapsulates it into a function because of the need for browser judgment. In addition to being able to get an Ajax object outside of the function, you need to declare an asynchronous object created by a separate variable store function outside of the function, with the basic code structure as follows:

var xhr = getxhr ()    function  getxhr () {        null;         if (window. XMLHttpRequest) {            xhr  new  XMLHttpRequest ();        } Else {            new activexobject (' microsoft.xmlhttp ');        }         return xhr;    }

1.3.2. sending a GET request

The main code for sending the request is as follows:

Xhr.open (' Get ', URI,true);

The open () method can be understood as preparation, filling in the information before sending the request.

    • The first parameter location, which uses "get" to send a GET request.
    • The second parameter location, fill in the address of the sending request, if you need to carry the parameter value in the address when sending the GET request, you can pass the "? "The way to append the" Name=value "object
    • The third parameter position, which is a Boolean-type value. When the Boolean value is true, the server request is asynchronous, that is, the script executes the Send () method without waiting for the result of the server execution, but continues to execute the script code, when the Boolean value is False, the server request is synchronous, That is, the script executes the Send () method and waits for the result of the execution of the server to return, and if it times out during the wait, no longer waits, and then executes the script code that follows!

Note: This method does not have a real send request.

Once you are ready, you need to specify the event handler and finally complete the actual send request via the Send () method. The code structure is as follows:

Xhr.open (' Get ', ' xx.do?uname=bear ',true= fn;xhr.send (null);

1.3.3. sending a POST request

The main code to send the POST request is as follows:

Xhr.open (' Post ', URI,true);

The open () method fills in "post", indicating how the request is requested. The URI describes the destination of the request, but since the data submitted by the Post request is generally placed in the request body, the URI does not have to follow some parameters like the Get method. The third parameter is used to identify synchronous or asynchronous commits.

However, there is a very significant difference between the post submission method and the Get method, which is missing a message header message, "Content-type". So in the case of a POST request, you use the encoded form to add this description to the message header. The code is as follows:

Xhr.setrequestheader (' Content-type ', ' applicaton/x-www-form-urlencoded ');

When these preparations are done, the event response code is specified, and finally the request is actually sent through the Send () method. Get mode, the Send method does not require parameters, passing in null. However, when the post is submitted, it is necessary to pass in the data to be submitted by the form in the Send method, in the form of a string "Name=value".

The basic code structure for sending a POST request is as follows:

Xhr.open (' Post ', ' xx.  dotrue); Xhr.setrequestheader (' content-type ', ' applicaton/x-www-form-urlencoded ');  = fn;xhr.send (' uname = Bear ');

Summing up the above decomposition, the basic steps to summarize the client Ajax request are as follows:

    1. Creating an Ajax Object
    2. Set the necessary data before the Ajax object sends the request through the open () method
    3. Specify the method of the event response
    4. Call the Send () method to initiate the request

1.3.4. Writing server-side code

After the client sends the request through JavaScript code, the server side needs to provide the code for the response to be processed and the ability to return some of the data. For the server side, regardless of whether the request is issued by the browser, or the Ajax object emitted, there is not much difference, as long as the use of the GetParameter method to obtain data, call the business logic to process, return data. In this logic, only the third step will be slightly different from the previous one. Either return to the full page or return a short paragraph of text to explain it.

The server-side code structure is as follows: (determine if the user name is legitimate)

Importjava.io.IOException;ImportJava.io.PrintWriter;Importjavax.servlet.ServletException;Importjavax.servlet.http.*; Public classActionservletextendsHttpServlet { Public voidService (httpservletrequest request,httpservletresponse response)throwsservletexception, IOException {request.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out=Response.getwriter (); String URI=Request.getrequesturi (); String Action= Uri.substring (Uri.lastindexof ("/"), Uri.lastindexof ("."))); if(Action.equals ("/check_username") ) {String username= Request.getparameter ("username"); if("Wang Xiong". Equals (username)) {Out.println ("User name already exists"); }Else{out.println ("Can use"); }} out.close (); }}

1.3.5. Writing event handler functions

The client sends the request, the server returns the response, and the client receives the response and needs to process the information returned by the server. For HTML pages, the process of returning data is to use JavaScript code to place data in a location on an existing page. The return time of this response is captured by the system, so the event handler is specified before sending the request, and the invocation and execution are done by the system. To get the returned text, the ResponseText property of the Ajax object can be read.

The code structure of the event handler function is as follows:

xhr.onreadystatechange=function () {if(xhr.readystate = = 4 && xhr.status==200) {                = xhr.responsetext;                 // positioning DOM nodes, adding text, Implementing refreshes                 $ (' s2 '). InnerHTML = ';                        }    };

2. AJAX Coding issues

2.1. GET Request garbled problem

2.1.1. Why does it have garbled characters ?

The root cause of garbled characters lies in the different ways of encoding and decoding.

The Ajax object provided by IE will encode the request parameters using the GBK character set, while the other browsers will encode them using UTF-8. That is, different browsers have inconsistent data encoding when sending requests.

For the server, iso-8859-1 is used by default for decoding, which is declared in the Tomcat configuration file.

Therefore, the content by different browser encoding has generated a different result, and this result arrived at the server, and the use of a browser is not the same as the decoding method to parse, so in the server-side data from the moment it was taken from the beginning is wrong, so all subsequent processing is based on the wrong data, I'm sure I won't get the result.

To solve the garbled problem, you need to be in the client and server-side uniform encoding and decoding method.

2.1.2. Troubleshooting GET requests for garbled issues

Solving garbled problems requires consistent encoding and decoding on both the server side and the client. A GET request is implemented on the server side by modifying the configuration file to implement a server-side fixed decoding format of UTF-8. The encodeURI method of the JavaScript language can be used to encode the UTF-8 encoded format when the client makes a request, because the data is trailing in the URI. Steps are as follows

Step1, specifying a character set for decoding

Tomcat can modify the <connector uriencoding= "UTF-8" > in the Conf/server.xml file to allow Tomcat to decode in UTF-8 mode.

Step2, use encodeURI to encode the request address. encodeURI uses Utf-8 to encode the Chinese parameters in the request address

In fact, the root cause of the problem is IE's unique. After the modification is complete, restart Tomcat and run without IE to find the Chinese that can be submitted in the Get mode of the normal read form.

For IE

    var  uri = ' xxx '.  do uname= ' + $F (' username ');     xhr.open (' Get ', encodeURI (URI), true);

2.2. garbled problem with POST request

2.2.1. Why garbled characters are generated

The reason why the garbled problem is caused by the POST request is still the difference between encoding and decoding. Since all browsers are encoded using the UTF-8 method when they submit a post, the server side defaults to decoding using the Iso-8859-1 method. So only need to modify the server-side decoding format, to ensure that the UTF-8 way to connect to avoid garbled.

2.2.2. how to solve

Request.setcharacterencoding ("UTF-8");

Note: Firefox does not use this code because the browser tells the server in the sending request packet which way the data is encoded.

The common code format for avoiding garbled characters is as follows:

Server-side:

Request.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8");

Client:

function Check_username () {//Get Ajax Objectsvar xhr=getxhr (); //Send Requestvar uri= ' check_username.do?username= ' + $F (' username ')); Xhr.open (' Get ', encodeURI (URI),true); Xhr.onreadystatechange=function () {/*only XHR's readystate equals 4 o'clock, XHR obtains all the data returned by the server. */                     if(Xhr.readystate = = 4){                         if(Xhr.status = = 200){                             //correct datavar txt=Xhr.responsetext; $(' Username_msg '). InnerHTML =txt; }Else{                             //An error has occurred                             $(' Username_msg '). InnerHTML = ' Error validating user name ';                 }                     }                 }; $(' Username_msg '). InnerHTML = ' checking ... '; Xhr.send (NULL); }

The detailed introduction can also refer to the Ajax tutorial on W3cschool: http://www.w3cschool.cc/ajax/ajax-intro.html

Ajax, Ajax coding problems

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.