Native JavaScript wrapper an Ajax method

Source: Internet
Author: User

Calling Ajax

1<script type= "Text/javascript" src= "Ajax.js" ></script>2<script type= "Text/javascript" >3     //call the wrapped Ajax method4 Ajax ({5Method: "Get",6URL: "get.php",7Asyn:true,8Data: "user=zym&password=1234",9Fn:function(res) {Ten Console.log (res); One         } A     }); -</script>

Packaged Ajax method functions:

1 functionAjax (Myjson) {2     //New Ajax Object3     varXHR =NULL;4Window. XMLHttpRequest? (xhr=NewXMLHttpRequest ()):(xhr=NewActiveXObject ("Microsoft.XMLHTTP"));5     //define the data transfer method "get" or "post", if not written, then the default is to use "get" Method! 6     varmethod = Myjson.method| | " Get;7     //define the address of the data transfer! 8     varURL =Myjson.url;9     //defines how the data is loaded (synchronous or asynchronous), by default, using Ajax, which is loaded asynchronously! Ten     varAsyn = myjson.asyn| |true; One     //define the specific data for the transfer!  A     vardata =Myjson.data; -     //the way to execute after success!  -     varfn =Myjson.fn; the     //The first case: If the Get method is used and data is present, it executes: -     if(method== "Get" &&data) { -Xhr.open (method,url+ "?") +data+ "&" +math.random (), Asyn); -     } +     //The second case: If the Post method is used, and data is present, it executes: -     if(method== "POST" &&data) { + Xhr.open (Method,url,asyn); AXhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); at xhr.send (data); -}Else{ - xhr.send (); -     } -     //after the data transfer is successful -Xhr.onreadystatechange=function(){ in         if(xhr.readystate==4){ -             if(xhr.status>=200&&xhr.status<300){ to fn (xhr.responsetext); +}Else{ -Alert ("Program Error! "); the             } *         } $     }Panax Notoginseng}

Native JavaScript wrapper an Ajax method

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.