JavaScript Ajax Learning

Source: Internet
Author: User
Tags xml dom document

1.AJAX is asynchronous Javascript+xml.  The ability to request additional data from the server without uninstalling the page. The core of Ajax technology is the XMLHttpRequest object (XHR).

2.AJAX can only send requests to URLs in the same domain that use the same port and protocol.

3. Create the process to give to Ajax:

1. Create a Xhr object. ie7+ only need var xhr=new xmlhttprequest ()

2. Create a send request through the open () method.  Xhr.open (Type,url,false); False indicates whether to send an asynchronous request.

3. Send the request. Xhr.send (NULL). Here the Send method takes a parameter, which is the data to be sent as the request principal. If you do not need to send requests through the request principal, you must pass in NULL. When send () is called, the request is dispatched to the server.

Since this request is synchronous, the JavaScript code waits for the server to respond before proceeding, and when the response is received, the response data is automatically populated with the properties of the Xhr object, with the following properties: ResponseText: The text returned as the response body.

Responsexml: If the content type of the response is "text/xml" or "application/xml" This property will hold the XML DOM document containing the response data.

Status: The HTTP status of the response.

Description of the Statustext:http status.

After the response is received, the first step is to check the Status property, confirming that the response has been successfully returned. In general, HTTP status codes can be used as a success flag. In addition, the body code of 304 indicates that the requested resource has not been modified.

if (xhr.status>=200 && xhr.status<300 | | xhr.status==304) {                alert (xhr.responsetext);            }             Else {                alert ("unsuccessful" +xhr.status);            }

More often than not, the asynchronous request is sent in order for JavaScript to continue without waiting for a response. You can now detect the ReadyState property of the Xhr object. This property represents the current active phase of the request/response process. The following values are desirable for this property

0: Uninitialized, the Open () method has not been called.

1: Start. The open () method has been called, but the Send () method has not been called.

2: Send. The Send () method has been sent, but the response has not been received.

3: Receive. Part of the response data has been received.

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

The ReadyStateChange event is triggered whenever the ReadyState property value is changed from one value to another. However, you need to specify the ReadyStateChange event handling before calling the open () method to ensure cross-browser compatibility.

Each HTTP request and response will have the appropriate header information. Use the setRequestHeader () method to set the custom request header information. Accepts two parameters: the name of the header field and the value of the header field. We recommend that you use a custom header field name.

xhr.onreadystatechange=function() {        if(xhr.readystate==4) {            if (xhr.status>=200 && xhr.status<300 | | xhr.status==304) {                alert (xhr.responsetext);            }             Else{                alert ("unsuccessful" +xhr.status);     }}}

GET Request:

Get is the most common type of request and is used to query the server for some information. If necessary, the query string parameter can be appended to the end of the URL to send the information to the server. An error often occurs when a GET request is used. There is a problem with the format of the query string. The name and value of each parameter in the query string must be encoded using encodeurlcomepotent. and all name-value pairs must be divided by &.

The following methods can assist in adding query string parameters to the end of the URL:

  function Addurlparam (url,name,value) {            URL+ = (Url.indexof ("?") = =-1? "?": "&");            URL+=encodeuricomponent (name) + "=" +encodeuricomponent (value);             return URL;        }

POST request:

Post requests are typically used to send data to the server that should be saved. The POST request should submit the data as the principal of the request, and the request body can contain very much data.

By default, server requests for post requests and submitted Web forms are not treated equally. Therefore, the server side must have a program to read the raw data sent over and parse out the useful parts from it. However, you can use XHR to spell the content type when the form is submitted.  Next, create a string in the appropriate format. If you need to serialize the data for the form in the page and then send it to the server, you can use serialize () to create the string.

  Xhr.open ("Post", "postexample.php",true);        Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");         var form=document.getelementbyid ("User-info");        Xhr.send (serialize (form)); // Send data in a form with ID user-info to the server after serialization

Formdata type

The Formdata type facilitates the serialization of forms and the creation of the same data as form formats.

The following code creates a Formdata type

var data=New  FormData ();    Data.append ("name", "value");

The convenience of using formdata is that it is not necessary to explicitly set the request header on the Xhr object, the Xhr object is able to recognize that the incoming data type is an instance of Formdata and configures the appropriate header information.

The code is summed up as follows:

var xhr=new xmlhttprequest ();
Xhr.onreadystatechange=function () {
if (xhr.readystate==4) {
if (xhr.status>=200 && xhr.status<300 | | xhr.status==304) {
alert (Xhr.responsetext);
}
else{
Alert ("unsuccessful" +xhr.status);
}
}
}
function Addurlparam (url,name,value) {
url+= (Url.indexof ("?") = =-1? "?": "&");
Url+=encodeuricomponent (name) + "=" +encodeuricomponent (value);
return URL;
}

Xhr.open ("Post", url,true);
Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
var Form=document.getelementbyid ("User-info");
Xhr.send (new FormData);//Send the data in the form with ID user-info to the server after serialization

Summarize the steps to create Ajax:

1. Create a XMLHttpRequest object,

2. Create an HTTP request and specify the method, URL, and request mode for the HTTP request.

3. Create a function that responds to changes in the state of the HTTP request.

4. Send an HTTP request.

5. Gets the data returned by the asynchronous call.

6. Use JS and Dom for local refresh.

  

JavaScript Ajax Learning

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.