Examples show how to use native JavaScript to process AJAX requests. Examples show ajax

Source: Internet
Author: User

Examples show how to use native JavaScript to process AJAX requests. Examples show ajax

Ajax is short for Asynchronous JavaScript and XML, and is a mechanism for updating a part of a page. It gives you the power to update a part of the page after obtaining data from the server, thus avoiding refreshing the entire page. In addition, partial page Updates can not only effectively create a smooth user experience, but also reduce the server load.

The following section analyzes a basic Ajax request:

var xhr = new XMLHttpRequest();xhr.open('GET', 'send-ajax-data.php');xhr.send(null);

Here, we create an instance of classes that can send HTTP requests to the server. Then, call the open method. The first parameter is the HTTP request method, and the second parameter is the URL of the Request page. Finally, we call the send method with the parameter null. If the POST request method is used (GET is used here), the parameters of the send method should contain any data you want to send.

The following describes how to handle the server response:

Xhr. onreadystatechange = function () {var DONE = 4; // readyState 4 indicates that the request var OK = 200 has been sent to the server; // status 200 indicates that the server returns success if (xhr. readyState === DONE) {if (xhr. status = OK) {console. log (xhr. responseText); // This is the returned text} else {console. log ("Error:" + xhr. status); // an error occurred in this request }}}

Onreadystatechange is asynchronous, which means it can be called at any time. This type of function is called a callback function. Once some processing is completed, it will be called. In this case, this processing occurs on the server.

Example

The convenient Ajax method is also the reason why many people rely on jQuery. However, in fact, the Ajax api of native JavaScript is also very powerful, and the basic usage is not very different in various browsers, therefore, you can encapsulate an Ajax object by yourself. The following is the encapsulated Ajax object:

// Ajax method // 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 not supported by this browser") ;}}return createXHR () ;}// Ajax executes the function request (aja XData) {var xhr = createXHR (); ajaxData. before & ajaxData. before (); // handle asynchronous request xhr through events. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {if (ajaxData. dataType = 'json') {// obtain the json object jsonStr = xhr returned by the server. responseText; json1 = eval ('+ jsonStr +'), json2 = (new Function ('Return '+ jsonStr) (); ajaxData. callback (json2); // ajaxData. callback (JSON. parse (xhr. ResponseText); // native method, which is not supported by IE6/7} else ajaxData. callback (xhr. responseText);} else {ajaxData. error & ajaxData. error (xhr. responseText) ;}}; // set the request parameter 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);} el Se {?? 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 ;}

The following is an example:

Index.html

<! Doctype html> Ajax.html
<! Doctype html> 

You can view the complete Demo for specific results.


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.