Examples of how to handle AJAX requests using native JavaScript _javascript tips

Source: Internet
Author: User

Ajax is a shorthand for asynchronous JavaScript and XML, a mechanism for updating parts of a page. It gives you the power to update a part of the page after getting the data from the server, thus avoiding refreshing the entire page. In addition, the local updating of the page in this way can not only effectively create a smooth user experience, but also reduce the load on the server.

The following is an analysis of a basic Ajax request:

var xhr = new XMLHttpRequest ();
Xhr.open (' Get ', ' send-ajax-data.php ');
Xhr.send (NULL);

Here, we create an instance of a class that can send HTTP requests to the server. It then calls its open method, where the first parameter is the HTTP request method, and the second parameter is the URL of the requesting page. Finally, we call the Send method with the parameter null. If you use the POST request method (where we use get), then the parameters of the Send method should contain any data you want to send.

Here's how we handle the server response:

Xhr.onreadystatechange = function () {
 var done = 4;//ReadyState 4 represents a request sent to the server
 var OK =/Status 200 represents server return Success
 if (xhr.readystate = = done) {
  if (xhr.status = = OK) {
   console.log (xhr.responsetext);//This is the returned text
  } else{
   Console.log ("Error:" + xhr.status); Error occurred in this request}}

onReadyStateChange is asynchronous, then this means that it will be invoked at any time. This type of function is called a callback function-it is invoked once some processing has been completed. In this case, this processing occurs on the server.

Example

The handy Ajax approach is also why many people rely on jQuery, but the Ajax API for native JavaScript is also powerful, and the basic usage is not very different in each browser, so it's possible to encapsulate an Ajax object in its own right, with the following encapsulated Ajax objects:

Ajax method//Lazy Load Create xhr object function Createxhr () {if (' XMLHttpRequest ' in window) {createxhr = function () {
  return new XMLHttpRequest ();
 
 };
  else if (' ActiveXObject ' in window) {createxhr = function () {return new ActiveXObject ("Msxml2.xmlhttp");
 
 };
  else {createxhr = function () {throw new Error ("Ajax is isn't supported by this browser");
 
 };
 
return createxhr ();
 
 }//Ajax execution function request (Ajaxdata) {var xhr = createxhr ();
 
 Ajaxdata.before && Ajaxdata.before (); Handle asynchronous requests through events Xhr.onreadystatechange = function () {if (xhr.readystate = 4) {if (Xhr.status =) {if (Ajaxdata.datatype = ' json ')
     {//Get the JSON object returned by the server Jsonstr = Xhr.responsetext;
     Json1 = eval (' + jsonstr + '), Json2 = (new Function (' return ' + Jsonstr)) ();
     Ajaxdata.callback (Json2); Ajaxdata.callback (Json.parse (Xhr.responsetext)); Native method, IE6/7 does not support} else Ajaxdata.callback (XHR.REsponsetext);
   else {ajaxdata.error && ajaxdata.error (xhr.responsetext);
 
 }
  }
 };
 
 Set Request Parameters Xhr.open (Ajaxdata.type, Ajaxdata.url);
 
 if (Ajaxdata.nocache = = True) xhr.setrequestheader (' if-modified-since ', ' 0 ');
  if (ajaxdata.data) {xhr.setrequestheader (' content-type ', ' application/x-www-form-urlencoded ');
 
 Xhr.send (Ajaxdata.data);  
  } else {??
  Xhr.setrequestheader (' X-requested-with ', ' XMLHttpRequest ');
 Xhr.send (NULL);
return XHR;
 
 Function post (ajaxdata) {Ajaxdata.type = ' post ';
 
 var _result = Request (Ajaxdata);
return _result;
 
 } function Get (ajaxdata) {ajaxdata.type = ' get ';
 
 Ajaxdata.data = null;
 
 var _result = Request (Ajaxdata);
return _result;
 }

Here is an example of the use:

Index.html

<! DOCTYPE html>  
Ajax.html
<! DOCTYPE html>
 
 

The concrete effect can browse the complete Demo.


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.