1. 程式人生 > >JavaScript的Ajax封裝GET和POST

JavaScript的Ajax封裝GET和POST

ror lis else ready .data 轉換 i++ stat try

<!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