Deep understanding of Ajax_javascript techniques in JavaScript

Source: Internet
Author: User

Ajax is not a new programming language, but a new way of using existing standards. Ajax can exchange data with the server without reloading the entire page. This kind of asynchronous interaction allows the user to click and get new data without refreshing the page.

XMLHttpRequest objects

The core of Ajax is the XMLHttpRequest object (XHR). XHR provides an interface for sending requests to the server and for analyzing the server response. Ability to get new data from the server asynchronously.

Create objects in the browser (only IE7 and higher versions are supported):

 
 

The use of XHR

The first thing to introduce is the open () method. It receives 3 parameters:

• The type of request to send (POST, GET, etc.)

• URL of the request

• Boolean value that indicates whether the request is sent asynchronously

Call the Open () Example:

Xhr.open ("Get", "index.jsp", false);
Get request for index.jsp. The URL is relative to the current page that executes the code; calling the open () method does not actually send the request, it simply initiates a request for sending.

Call send () Sending request:

Xhr.send (NULL);

Send () receives a parameter, which is the data to be sent as the request body. If you do not need to send data through the request body, you must pass in NULL.

The corresponding data is populated with the related properties of the XHR object:

responsetext: Text returned as a response body

Responsexml: The content type in response is "text/xml" or "Application/xml"

Status: HTTP status of the response

Description of statustext:http status

After receiving the response, first check the Status property to determine that the response has been returned, typically 200 as a sign of success. Status Code 304 indicates that the resource is not modified and can be used directly from the cached version in the browser.

In order to receive the appropriate response, two status codes should be detected in the following ways:

Xhr.open ("Get", "index.jsp", false);
Xhr.send (null);
if ((Xhr.status >= && xhr.status <) | | xhr.status = = 304) {
alert (xhr.responsetext);
} else {
alert ("Request was unsuccessful:" + Xhr.status);
}

By detecting the ReadyState property, you can determine the current active phase of the request/response process.

• 0: Uninitialized. The open () method is not called

• 1: Start up. The open () method was called, and the Send () method was not invoked

• 2: Send. The Send () method has been called and no response was received

• 3: Receive. Some of the data has been received

• 4: Complete. All data has been received and can be used on the client

When the value of the ReadyState property changes, a ReadyStateChange event is triggered. Specify the onReadyStateChange event handler before calling open () to ensure browser compatibility.

var xhr = new XMLHttpRequest ();
Xhr.onreadystatechange = function () {
if (xhr.readystate = 4) {
if (xhr.status >= && xhr.status < 300) | | Xhr.status = = 304) {
alert (xhr.responsetext);
} else {
alert ("Successful request: + Xhr.status";
}}}
;
Xhr.open ("Get", "index.jsp", true);
Xhr.send (NULL);

You can cancel an asynchronous request before receiving a response:

Xhr.abort ();

HTTP header information

The XHR object provides a way to manipulate the request header and respond to the header information.

By default, the following header information is also sent when the XHR request is sent.

Accept: Types of content that browsers can handle

Accept-charset: The character set that the browser can display

accept-encoding: The compression code that the browser can handle

Accept-language: The language currently set by the browser

Connection: Type of connection between browser and server

Cookie: Any Cookie for the current page setup

Host: The domain where the requested page is located

referer: URL of the page that issued the request

user-aent: User agent string for browser

Use setRequestHeader () to set custom request header information. Must be called after the Open () method is called and before send () is invoked.

setRequestHeader ():

Xhr.open ("Get", "index.jsp", true);
Xhr.setrequestheader ("MyHeader", "myvalue");

Call getResponseHeader () and pass in the field name to get the appropriate response header information. Getallresponseheader () Gets a long string containing all the header information.

var myheader = Xhr.getresponseheader ("MyHeader");
var allheaders = Xhr.getallresponseheader ();

GET request

Get is used to query certain information to the server. Query string parameters can be appended to the end of the URL, and the name and value of each parameter in the query string must be encoded using encodeURIComponent ():

Xhr.open ("Get", "login.jsp?name1=value1&name2=value2", false); 
Addurlparam () receives three parameters: the URL to which to add the parameter, the name of the parameter, and the value of the parameter.
var url = "login.jsp";
Add parameter
url = addurlparam (URL, "username", "xxyh");
url = addurlparam (URL, "password", "xxyh123");
Initialize request
Xhr.open ("Get", url, false);

POST request

Post requests are used to send data to the server that should be saved. The body of a POST request can contain very much data, and the format is not limited.

Initialization request:

Xhr.open ("Post", "login.jsp", true); 
First, set the Content-type header information to application/x-www-form-urlencoded, and then create a string format. If you need to serialize the form data in a page and then send it to the server via XHR, you can use the Serialize () function to create this string:
xhr.open ("Get", "login.jsp", false);
Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
var form = document.getElementById ("User-info");
Xhr.send (Form) (serialize);

The above is a small set to introduce the JavaScript in the Ajax in-depth understanding, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.