Several methods of JavaScript implementing native Ajax

Source: Internet
Author: User

Since JS has a variety of frameworks, such as jquery, the use of Ajax has become quite simple. But sometimes in order to pursue brevity, there may be no need to load jquery's huge JS plugin in the project. But what about the ability to use AJAX? Here are a few ways to implement native Ajax using JavaScript.

You must create an XMLHttpRequest object before you implement Ajax first. If you do not support the browser that created the object, you need to create a activexobject, as follows:

var xmlhttp;function createxmlhttprequest () {if (window. ActiveXObject) {xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP");} else if (window. XMLHttpRequest) xmlhttp=new XMLHttpRequest ();}

(1) The simplest AJAX GET request is implemented using the XMLHTTP created above:

function doget (URL) {//Note when passing parameter values, it is best to use encodeuri processing, to prevent garbled createxmlhttprequest (); Xmlhttp.open ("GET", url); Xmlhttp.send (null); Xmlhttp.onreadystatechange=function () {if (xmlhttp.readystate==4&&xmlhttp.status==200 {Alert (' Success ');} Else{alert (' fail ');}}}

(2) Use the XMLHTTP created above to implement the simplest Ajax POST request:

function DoPost (url,data) {//Note it is best to use encodeURI when passing parameter values to prevent garbled createxmlhttprequest (); Xmlhttp.open ("POST", url); Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send (data); Xmlhttp.onreadystatechange=function () {if (xmlhttp.readystate==4&&xmlhttp.status==200) {alert (' Success ');} Else{alert (' fail ');}}}

(3) below to share a package of $.ajax methods for simulating jquery seen from the Web:

Var createajax=function () {    var xhr=null;    try{//ie series browser         xhr=new activexobject ("Microsoft.XMLHTTP");     }catch (E1) {        try{//non-IE browser              xhr=new xmlhttprequest ();         }catch (E2) {             Window.alert ("Your browser does not support Ajax, please replace it!") ");         }    }    return  xhr;}; Var ajax=function (conf) {    var type=conf.type;//type parameter, optional       var url=conf.url;//url parameters, required      var data=conf.data;//data parameters are optional, The      var datatype=conf.datatype;//datatype parameter is optional only when the POST request is required      var success=conf.success;//callback function optional     if (type==null) {//type parameter optional, The default is get        type= "Get";    }     if (datatype==null) {//datatype parameter optional, default = text        datatype= "Text" ;     }    var xhr=createajax ();     xhr.open ( Type,url,true);     if (type== "GET" | | type== "Get") {        xhr.send (null);     }else  if (type== "POST" | | type== "Post") {        xhr.setrequestheader ("Content-type", "Application /x-www-form-urlencoded ");         xhr.send (data);     }    xhr.onreadystatechange=function () {         if (xhr.readystate==4&&xhr.status==200) { &NBSp;          if (datatype== "Text" | | datatype== "TEXT") {                 if (success!=null) {//Plain text                      success (Xhr.responsetext);                 }             }else if (datatype== "xml" | | datatype== "XML") {                 if (success!=null) {//Receive XML documents                      success (Xhr.responsexml);                 }        & NBsp;   }else if (datatype== "JSON" | | datatype== "JSON") {                 if (success!=null) {//Convert JSON string to JS object                      success (eval ("+xhr.responsetext+"));                 }             }        }     };};

This method is also very simple to use, like jquery's $.ajax method, but not so many parameters. It simply implements some basic AJAX functionality. Here's how to use it:

Ajax ({type: "POST",//post or get, non-mandatory URL: "test.jsp",//Required data: "Name=dipoo&info=good",//Must not DataType: "JSON",    Text/xml/json, non-mandatory success:function (data) {///callback function, non-mandatory alert (data.name); }});



Several methods of JavaScript implementing native Ajax

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.