function obj2str(data) { data = data || {}; // 若是沒有傳參, 爲了添加隨機因子,必須本身建立一個對象 data.t = new Date().getTime(); var res = []; for (var key in data){ //在URL中是不能夠出現中文的,若是出現了中文須要轉碼,能夠調用encodeURIComponent方法,URL中只能夠出現字母、數字、下劃線 res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key])); } return res.join("&"); } function myAjax(option){ var params = obj2str(option.data);//key=value&key=value; var xmlhttp,timer; if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else{// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } if (option.type.toUpperCase()==="GET") {//toLowerCase將大寫轉化爲小寫 xmlhttp.open("GET",option.url+"?"+params,true) xmlhttp.send(); }else{ xmlhttp.open("POST",option.url,true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send(params); } xmlhttp.onreadystatechange = function (ev2) { if (xmlhttp.readyState === 4){ clearInterval(timer); //判斷是否請求成功(Http狀態碼大於等於200,且小於300,和狀態碼等於304爲請求成功) if (xmlhttp.status>=200&&xmlhttp.status<300||xmlhttp.status===304) { option.success(xmlhttp); }else{ option.error(xmlhttp); } } }; if (option.timeout){ timer = setInterval(function () { console.log("中斷請求"); xmlhttp.abort(); clearInterval(timer); },option.timeout); } }