Summary of Ajax issues (for Java)

Source: Internet
Author: User

1. What is Ajax?

Asynchronous JavaScript and XML (asynchronous JavaScript and XML)

Ajax is a technique used to improve the user experience by asynchronously sending a request to the server via a browser-provided Ajax object (that is, the XMLHttpRequest object), which returns part of the data instead of a full page, changing the local data in the page without refreshing the page.

Key points: 1. Browser-side pages are not destroyed

2. The browser sends the request to the server while the user can continue the Operation page

3. The page is only a partial update, not an entire page

A 4.AJAX object is a XMLHttpRequest object (both of which are the same object).

5.XMLHttpRequest is a browser-provided object

6. Network Transmission Performance Improvement (the network no longer transmits the entire page, but transmits some of the data, avoids the large amount of redundant data transmission occupies the network bandwidth)

7. An Ajax object sends a request to the server and a request returned by the receiving server, so the Ajax object provides properties and methods that can handle the requests sent and the requests received.

 

2. How do I get an Ajax object?

function Getxmlhttprequest () {

var xhr=null;

if (window. XMLHttpRequest) {

This method is suitable for non-IE browsers, such as Firefox, Chrome .....

xhr=New XMLHttpRequest ();

}else{

This method is suitable for IE browser

xhr=new ActiveXObject (' microsoft.xmlhttp ');

}

return XHR;

//NOTE: IE supports XMLHttpRequest (IE11) (ActiveXObject () mode) from the beginning of the

The idea of Ajax was originally proposed by Microsoft and used ActiveXObject () to obtain Ajax objects, followed by a unified XMLHttpRequest () method to obtain Ajax objects, so other browser vendors unified for use// XMLHttpRequest () Gets Ajax objects, and Microsoft has insisted on using ActiveXObject () to get Ajax objects before IE11, and Microsoft has only supported XMLHttpRequest () methods to get Ajax objects since IE11.

}

3.AJAX objects provide a number of common properties and methods

1> Common Properties

(1) readystate

---represents the state of the request, that is, the state of the Ajax object communicating with the server

---A total of five values can be taken: 0,1,2,3,4

0---Indicates that 1 has not been initialized---indicates that a request 2 is being sent---indicates that the request completed 3---indicates that the request was successful and receiving the server response data

4---The data received successfully (this state is more important, indicating that the Ajax object has obtained all the data returned by the server, you can do the next step)

(2) onReadyStateChange

---indicates that the event handler for the onReadyStateChange property binding is triggered when readystate changes (note: The value of the onReadyStateChange property is an event handler)

(3) Status

---represents the response value of the HTTP request returned by the server

---commonly used return values are:

200: Request succeeded (OK) 202: Indicates the server has accepted the request, but processing is not completed (accept)

302: Express Redirect (Move temporarily)

400: Request for error (Bad Request) 404: Indicates resource not found (not Found)

500: Internal server errors (Internal server error)

(4) ResponseText

---indicates that the server is returning text information (which is used to return simple data information)

(5) Responsexml

---indicates that the server is returning XML (this is not commonly used now, and it is common to use JSON objects to return more complex data information)

Common methods of 2>

(1) open (Method,url,true/false);

---used to create a request

---method: Indicates the way of the request, commonly have get and post two ways;

---URL: Represents the requested address, and a GET request can specify request parameter information after the URL

---True: Represents the request server as an asynchronous request, False: Represents the request server as a synchronous request.

(2) Send ()

---used to send requests

---send (NULL): For GET request mode

---send (name=value&name=value ...) : Used for POST request, specifying request parameter information in parentheses

(3) setRequestHeader ()

---The HTTP header used to specify the request

(4) getResponseHeader ()

---used to get the specified HTTP header

(5) getAllResponseHeaders ()

---All HTTP headers used to get a response

(6) Abort ()

---used to cancel a request

4. Steps to use Ajax

1> Getting Ajax objects

2> Create request

3> Setting the callback function

4> Sending requests

5> Writing server-side code

Example Demo:

1> Getting Ajax objects

function Getxmlhttprequest () {

var xhr=null;

if (window. XMLHttpRequest) {

xhr=new XMLHttpRequest ();

}else{

xhr=new ActiveXObject (' microsoft.xmlhttp ');

}

return XHR;

}

2> Create request

(1) Get mode Create request

<script type= "Text/javascript" >
function Check () {
var xhr=getxmlhttprequest ();
xhr.open (' Get ', ' check.form?code=xxx ', true);
......
}
</script>

(2) Post mode creation request

<script type= "Text/javascript" >
function Check () {
var xhr=getxmlhttprequest ();
Xhr.open (' Post ', ' Check.form ', true);

Note: Because the HTTP protocol requires a CONTENT-TYPE message header when sending a POST request, it is necessary to explicitly specify the request message header when sending a POST request using an Ajax object

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

......

}
</script>

3> writing callback event handler functions

<script type= "Text/javascript" >
function Check () {
var xhr=getxmlhttprequest ();
Xhr.open (' Get ', ' check.form?code=xxx ', true);

Note: xhr.onreadystatechange=function () {...}; The function is to bind the event handler for the onReadyStateChange property, and when the readystate changes, it calls the processing logic inside the function for//corresponding processing.
xhr.onreadystatechange=function () {

Readystate==4 indicates that the Ajax object has obtained all the data returned by the server; STATUS==200 indicates successful request

The following judging conditions guarantee the integrity and correctness of the data
if (xhr.readystate==4 && xhr.status==200) {
var Txt=xhr.responsetext;
$ ("span_msg"). Innerhtml=txt;
}
};
......
}
</script>

4> Sending requests

(1) Get mode send request

<script type= "Text/javascript";
             & nbsp;   function Check () {
                 var xhr= Getxmlhttprequest ();
           Xhr.open (' get ', ' Check.form? Code=lily&pwd=123 ', true);
   xhr.onreadystatechange=function () {

if (xhr.readystate==4 && xhr.status==200) {
var Txt=xhr.responsetext;
$ ("span_msg"). Innerhtml=txt;
}
};

Send method passed NULL in GET request mode

       Xhr.send (NULL);
}
</script>

(2) Post mode send request

<script type= "Text/javascript" >
function Check () {
var xhr=getxmlhttprequest ();
Xhr.open (' Post ', ' Check.form ', true);

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

Xhr.onreadystatechange=function () {

if (xhr.readystate==4 && xhr.status==200) {
var Txt=xhr.responsetext;
$ ("span_msg"). Innerhtml=txt;
}
};

Passing parameters via the Send () method in the POST request mode

       Xhr.send (' code=lily&pwd=123 ');

}
</script>

5> Writing server-side code

Package web;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Actionservlet extends httpservlet{
@Override
protected void Service (HttpServletRequest req, httpservletresponse Res) throws Servletexception, IOException {
Req.setcharacterencoding ("Utf-8"); Set the server-side decoding mode to Utf-8, to prevent the occurrence of Chinese garbled
String Uri=req.getrequesturi (); Get Request Resource Path
String action=uri.substring (Uri.lastindexof ("/"), Uri.lastindexof (".")); Parse the request resource path to get the last/and last one in the path. The content between
Res.setcontenttype ("Text/html;charset=utf-8"); Set the server-side encoding method to Utf-8, prevent the occurrence of Chinese garbled

PrintWriter Out=res.getwriter ();
Depending on the results of the analysis, different treatments are carried out

//To learn to use the following method for equal judgment, the benefit is to prevent the system from throwing a null pointer exception when the action is empty.
if ("/login". Equals (action)) {
String code=req.getparameter ("code");
if (...) {

The server side returns part of the data to the Ajax object via the Out.println ("...") method, and the Ajax object can get the data returned by this method on the browser side through the ResponseText property value.

      OUT.PRINTLN ("Correct account, welcome login");

}else{

      Out.println ("Incorrect account, please re-enter");

}
}else (...) {

......

}
}
}

5. Application of Ajax

1> user-entered data needs to be verified (for example, if the user name entered by the user is checked for registration)

2> list of automatic prompts that appear when searching

3> cascading display (cascading menu)

4> Data entry and list display on the same page (for example: Create object/Modify object and Show all object records on same page)

5> do not need to refresh the page

Summary of Ajax issues (for Java)

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.