JavaScript ajax encapsulation Get and post

Source: Internet
Author: User

Tags: code    cal   dex   ext   creat    console   ack   rand   obj   

<! DOCTYPE html><html><head> <title> Package Ajax</title></head><body><script Type= "Text/javascript" > Function createxhr () {if (typeof XMLHttpRequest! = "undefined") {return new XMLHttpRequest (); } else if (typeof activexobject! = "undefined") {var versions = ["msxml.2.xmlhttp.6.0", "msxml.2.xmlhttp.3.0", "MSXML.2". XMLHttp "]; for (var i = 0; i<versions.length;i++) {try{return new ActiveXObject (Version[i]);} catch (E) {//Because the class loop will report a mistake, skip some errors}}} else {throw new Error ("Your system or browser does not support XHR objects! "); } } The name value pair converts the string function params (data) {var arr = []; for (var i in data) {Arr.push (encodeURIComponent (i) + "=" +encodeuricompone NT (Data[i])); } return Arr.join ("&"); }//Ajax function Ajax (obj) {var xhr=createxhr (); obj.url=obj.url+ "? rand=" +math.random (); obj.data = params (obj.data); I F (Obj.method = = = "GET") {Obj.url+=obj.url.indexof ("?") = =-1? "?" + Obj.data: "&" +obj.data; }//If it ' s asynchronous if (Obj.async = = = True) {Xhr.onreadystatechange = funCtion () {if (xhr.readystate = = 4) {callback ();}}} Xhr.open (Obj.method,obj.url,obj.async); if (Obj.method = = = "POST") {Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Xhr.send ( Obj.data); } else {xhr.send (null);}//If It's synchronization if (Obj.async = = = False) {callback ();}//encapsulation repeating calling code function Callbac K () {if (xhr.status = = =) {obj.success (xhr.responsetext);} else {alert ("Error code:" +xhr.status+ "-Error message:" +xhr.statustext) ; }}}//Use Ajax AddEventListener ("click", Function () {Ajax ({method: "POST", url: "test.php", data:{"Na&me": "Ping", "a GE ": 18},//Upload object to text, then object callback Success:function (text) {Console.log (" Receive success data: "+text);}, async:false}); },false);</script></body></html>

JavaScript ajax encapsulation get and post

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.

Tags Index: