码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript的Ajax封装GET和POST

时间:2018-09-05 18:06:53      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:代码   cal   dex   ext   creat   console   ack   rand   obj   

<!DOCTYPE html> <html> <head> <title>封装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){ // 因类循环会报一个错,跳过些错 } } } else { throw new Error("你的系统或浏览器不支持XHR对象!"); } } // 名值对转换字符串 function params(data) { var arr = []; for(var i in data) { arr.push(encodeURIComponent(i)+"="+encodeURIComponent(data[i])); } return arr.join("&"); } // ajax function ajax(obj) { var xhr=createXHR(); obj.url=obj.url+"?rand="+Math.random(); obj.data = params(obj.data); if(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(); } // 封装重复调用代码 function callback() { if(xhr.status === 200) { obj.success(xhr.responseText); } else { alert("错误代码:"+xhr.status+"-错误信息:"+xhr.statusText); } } } // use ajax addEventListener("click",function(){ ajax({ method:"POST", url:"test.php", data:{ "na&me":"ping", "age":18 }, // 将对象传到text,然后对象又回调 success:function(text) { console.log("接收success数据为:"+text); }, async:false }); },false); </script> </body> </html>

JavaScript的Ajax封装GET和POST

标签:代码   cal   dex   ext   creat   console   ack   rand   obj   

原文地址:http://blog.51cto.com/9535003/2170722

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!