Javaweb Small knowledge learning--native Ajax

Source: Internet
Author: User

The role of Ajax local refresh, as the promotion of the page experience is very important, but everyone said that SEO is not very friendly, has been using jquery encapsulated Ajax, did not know what the original is like, hereby learning, supplementary knowledge

1. Get mode of native Ajax

A label is defined on the page. The effect you want to achieve click the A tab to be able to request the server and eject the fields returned by the server

<body>    <a href="/ajaxTest">点击我!</a></body>

The corresponding Ajax request is as follows, the comment step is very detailed

Specific functions can refer to the final appendix, the letter number is explained in detail<script>Window.onload = function () {document.getElementsByTagName (' A ')[0].onclick = function () {            //1. Creating a request XMLHttpRequest Object            varRequest =NewXMLHttpRequest ();//2. How to request the link and request            varURL ='/ajaxtest ';//link to request            varMETHOD =' GET ';//3. Preparing requests using the Open methodRequest.open (Method,url,true);//4. Sending a request using send, the Get method transmits null, if the delivery content is not NULL, the request is guaranteed to be postRequest.send (NULL);//5. Call read to listen for request statusRequest.onreadystatechange = function () {                //6. Indicates that the request is complete              if(Request.readystate = =4){//Indicates the result of the request is correct                  if(Request.status = = $|| Request.status = =304) {alert (request.responsetext); }              }            };//Block a link jump            return false; }    };</script>

Server-side counterpart output Hello World

   @RequestMapping"ajaxTest",method = {RequestMethod.GET,RequestMethod.POST})    publicvoidgzipTestthrows IOException {        "Hello World";        ServletOutputStream sos = response.getOutputStream();        sos.write(str.getBytes());    }

At the same time the browser will generate requests

2. Native Ajax Post mode

The Post method is simple
1. Change the method to post
2. Called after the Open () function

//3.1表明这是一个post请求request.setRequestHeader("Content-type","application/x-www-form-urlencoded");

3. Application in Development

The vast majority of development does not use the native way, because to write too much code, can be encapsulated into a function, and then call is a good way, but the vast majority of people are packaged with others, such as jquery, as the understanding, the original way to understand

4. Property sheet

The concept is not written, the direct writing method

The request is to take advantage of the example of XMLHttpRequest, the following practical example of the method

1.onreadystatechange:

The event handler is triggered by the server , not the user
During Ajax execution, the server notifies the client of the current state of communication. This is accomplished by updating the readyState of the XMLHttpRequest object. Changing the ReadyState property is a way for the server to connect to the client. The ReadyStateChange event is triggered every time the ReadyState property is changed

2.open (method, URL, asynch)

The open method of the XMLHttpRequest object allows the programmer to send a request to the server with an Ajax call.
method: The request type, a string similar to "GET" or "POST". If you want to retrieve only one file from the server without sending any data, use get (you can send the data in a GET request by appending the query string to the URL, but the data size is limited to 2000 characters). If you need to send data to the server, use post. In some cases, some browsers cache the results of multiple XMLHttpRequest requests at the same URL. If the response to each request is different, it will result in bad results. When you append the timestamp to the end of the URL, you can ensure that the URL is unique, thus avoiding the browser caching the results.
URL: A path string that points to the file on the server you requested. Can be either an absolute path or a relative path.
Asynch: Indicates whether the request is to be transmitted asynchronously, and the default value is true. Specifies true to not wait for the server to be appropriate before reading the following script. Specifies false, when the script process passes this point, to stop until the AJAX request has been executed before proceeding.

3.send (data):

The Open method defines some details of the Ajax request. The Send method can send instructions for a request that is already on standby
data: The string that will be passed to the server.
If a GET request is selected, no data is sent and null is passed to the Send method: Request.send (NULL);
When supplying parameters to the Send () method, make sure that the method specified in open () is POST, and null is used if no data is sent as part of the request body.

4.setRequestHeader (Header,value)

When the browser requests a page from the server, it sends a set of header information along with the request. The header information is a series of metadata that describes the request (metadata). The header information is used to declare whether a request is a GET or POST.
In an Ajax request, the job of sending the header information can be done by setRequestHeader
parameter Header: The name of the header; The value of the parameter value: header.
If you send data to the server with a POST request, you need to set the header of "Content-type" to "application/x-www-form-urlencoded". It tells the server that the data is being sent and that the data is already URL-encoded.
The method must be open () before calling the

5.readyState

The ReadyState property represents the current state of the AJAX request. Its value is represented by a number.
0 represents uninitialized. The Open method has not been called
1 represents loading. The open method has been called, but the Send method has not yet been called
2 indicates that the load is complete. Send has been called. The request has started
3 represents the interaction. The server is sending a response
4 represents complete. Response sent complete
Each time the ReadyState value changes, the ReadyStateChange event is triggered. If the onReadyStateChange event handler is assigned to a function, then each change in the ReadyState value causes the function to execute.
Changes in the ReadyState values vary depending on the browser. However, when the request is finished, each browser will set the value of the readyState to 4 uniformly

6.status

Each response sent by the server also comes with a header message. The three-digit status code is the most important header information in the response sent by the server and is part of the Hypertext Transfer Protocol.
Common status codes and their meanings:
404 Page Not Found (not found)
403 No access (forbidden)
500 Internal server error (internal service error)
2001 Cut Normal (OK)
304 Not modified (not modified)
In the XMLHttpRequest object, the status codes sent by the server are saved in the status attribute. By comparing this value to 200 or 304, you can ensure that the server has sent a successful response

7.responseText

The ResponseText property of XMLHttpRequest contains the data sent from the server. It is a html,xml or plain text, depending on what the server sends.
When the ReadyState property value becomes 4 o'clock, the ResponseText property is available, indicating that the AJAX request has ended.

8.responseXML

If the server returns XML, the data is stored in the Responsexml property.
The Responsexml property is available only when the server sends data with the correct header information. The MIME type must be Text/xml

Javaweb Small knowledge learning--native Ajax

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.