Js-ajax and Comet

Source: Internet
Author: User
Tags xml dom document

Ajax and Comet:

1, the core of Ajax technology is XHR (XMLHttpRequest object)

To create a XHR object:

function Createxhr () {

if (typeof XMLHttpRequest! = "undefined") {

return new XMLHttpRequest ();

}else if (typeof activexobject! = "undefined") {

if (typeof arguments.callee.activeXString! = "string") {

var versions=["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.3.0", "Msxml2.xmlhttp"],

I,len;

for (i=0,len=versions.length;i<len;i++) {

try{

New ActiveXObject (Versions[i]);

Arguments.callee.activexstring=versions[i];

Break

}catch (ex) {

Skip Over

}

}

}

return new ActiveXObject (arguments.callee.activeXString);

}else{

throw new Error ("No XHR object available.");

}

}

2. Using XHR object: Open (), send ()

1) The Open () method, which receives 3 parameters, the request type to be sent, the URL of the request, the Boolean value that indicates whether the request was sent asynchronously

Xhr.open ("Get", "example.php", false);

Calling the open () method does not actually send the request, but only initiates a request for sending

2) to send a specific request, you must call the Send () method as follows:

Xhr.open ("Get", "example.php", false);

Xhr.send (NULL);

The Send () method receives a parameter, which is the data to be sent as the request principal, and must pass in NULL if it is not necessary to send the data through the request body, which is required for some browsers, and after the Send () method is called, the request is dispatched to the server

3) When the request is synchronized, the JS 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

ResponseText: Text returned as the response body

Responsexml: If the content type of the response is "text/xml" or "Application/xml", the XML DOM document containing the response data will be saved in this property

Status: HTTP status of the response

Description of the Statustext:http status

Once the response is received, the first step checks the status property to determine that the response has returned successfully.

if ((xhr.status>=200 && xhr.status<300) | | xhr.status==304) {

The HTTP status code is 200 as a success token

A status code of 304 indicates that the requested resource has not been modified and can be used directly from the cached version in the browser

alert (Xhr.responsetext);

}else{

Alert ("Request was unsucessful:" + xhr.status);

}

4) Send an asynchronous request to detect the ReadyState property of the Xhr object, representing the current active phase of the request/response process

The values that are desirable for the property:

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

1: Started, the Open () method has been called, but the Send () method has not been called

2: Send, the Send () method has been called, but the response has not been received

3: Received, the partial response data has been received

4: Completed, has received all the response data, and has been used in the customer service side

You must specify the onReadyStateChange event handler before calling the open () method to ensure cross-browser compatibility

var xhr=createxhr ();

Xhr.onreadystatechange=function () {

if (xhr.readystate==4) {

if ((xhr.status>=200 && xhr.status<300) | | xhr.status==304) {

alert (Xhr.responsetext);

}else{

Alert ("Request was unsucessful:" + xhr.status);

}

}

};

Xhr.open ("Get", "Example.js", true);

Xhr.send (NULL);

5) Call the Xhr.abort () method, the Xhr object stops triggering the event, and no longer allows access to any object properties related to the response

3, HTTP header information: Each HTTP request and response will have the corresponding header information, the XHR object provides the operation of the two types of head (Request header and response header) Information method

1) By default, the following header information is also sent when the XHR request is sent:

Accept: Content types that the browser can handle

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

Accept-encoding: Compression encoding that the browser can handle

Accept-language: The language currently set by the browser

Connection: Type of connection between browser and server

Cookies: Any cookie that is set on the current page

Host: The domain of the page where the request was made

Referer: URI of the page that made the request

User-agent: User agent string for browser

2) using the setRequestHeader () method, you can set the custom request header information, receive 2 parameters: the name of the header field, the value of the header field, the method is placed after open (), and before Send ()

3) The Getrequestheader () method obtains the corresponding response header information, the getAllResponseHeaders () method can obtain a long string containing all header information

var myheader=xhr.getresponseheader ("MyHeader");

var allheader=xhr.getallresponseheader ();

4, the name of each parameter in the query string and the value need to be encoded using encodeuricomponent, and then placed at the end of the URI, and all the name value pairs must be separated by &

Xhr.open ("Get", "example.php?name1=value1&name2=value2", true);

function Addurlparam (url,name,value) {

url+= (Url.indexof ("?") ==-1? "?": "&");

Url+=encodeuricomponent (name) + "=" +encodeuricomponent (value);

return URL;

}

5. Post:

var xhr=createxhr ();

Xhr.onreadystatechange=function () {

if (xhr.readystate==4) {

if ((xhr.status>=200 && xhr.status<300) | | xhr.status==304) {

alert (Xhr.responsetext);

}else{

Alert ("Request was unsucessful:" + xhr.status);

}

}

};

Xhr.open ("Get", "Example.js", true);

Xhr.setrequesthander ("Content-type", "application/x-www-form-urlencoded");

var Form=document.getelementbyid ("User-info");

Xhr.send (serialize (form));

6, FormData

var data=new FormData ();

Data.append ("name", "Zhang");

Incoming form elements

var data=new FormData (Document.forms[0]);

Direct to send

Xhr.open ("Get", "Example.js", true);

var Form=document.getelementbyid ("User-info");

Xhr.send (new FormData (form));

7. Timeout settings:

Xhr.open ("Get", "Example.js", true);

xhr.timeout=1000; Only available for ie8+

Xhr.ontimeout=function () {

Alert ("ddddddddd");

}

Xhr.send (NULL);

8. The Overridemimetype () method guarantees that the response is displayed as XML rather than plain text

Overridemimetype ("Text/xml")

9. Progress events:

1) for XHR operation:

Loadstart: Son, Trigger when the first byte of a response is received

Progress: constant triggering during receive response

Error: Triggered when a request has occurred

Abort: Triggered when a connection is terminated because the abort () method is called----used to stop an in-progress request

Load: Triggered when full response data is received

Loaded: Triggered after communication is complete or triggered Error,abort,load event

2) The OnProgress event handler must be added before open

var xhr=createxhr ();

Xhr.onload=function (event) {

if (((xhr.status>=200 && xhr.status<300) | | xhr.status==304) {

alert (Xhr.responsetext);

}else{

Alert ("Request was unsucessful:" + xhr.status);

}

};

Xhr.onprogress=function (event) {

var Divstatus=document.getelementbyid ("status");

if (event.lengthcomputable) {

Divstatus.innerhtml= "Received" +event.position+ "of" +event.totalsize+ "bytes";

}

Event.lengthcomputable Indicates whether progress information is available as a Boolean value

Event.position indicates the number of bytes that have been received

Event.totalsize The expected number of bytes determined by the Content-length response header

};

Xhr.open ("Get", "Example.js", true);

Xhr.send (NULL);

10. Set the Withcredentials property to True to specify that a request should send a request

11. Cross-browser Cors

Js-ajax and Comet

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.