// 使用原生js 封裝ajax// 相容xhr對象function createXHR(){if(typeof XMLHttpRequest != "undefined"){ // 非IE6瀏覽器return new XMLHttpRequest();}else if(typeof ActiveXObject != "undefined"){ // IE6瀏覽器var version = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp",];for(var i = 0; i < version.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("&");}// 封裝ajaxfunction ga_ajax(obj){var xhr = createXHR();obj.url = obj.url + "?rand=" + Math.random(); // 清除緩衝obj.data = params(obj.data); // 逸出字元串if(obj.method === "get"){ // 判斷使用的是否是get方式發送obj.url += obj.url.indexOf("?") == "-1" ? "?" + obj.data : "&" + obj.data;}// 非同步if(obj.async === true){// 非同步時候需要觸發onreadystatechange事件xhr.onreadystatechange = function(){// 執行完成if(xhr.readyState == 4){callBack();}}}xhr.open(obj.method,obj.url,obj.async); // false是同步 true是非同步 // "demo.php?rand="+Math.random()+"&name=ga&ga",if(obj.method === "post"){xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.send(obj.data);}else{xhr.send(null);}// xhr.abort(); // 取消非同步請求// 同步if(obj.async === false){callBack();}// 返回資料function callBack(){// 判斷是否返回正確if(xhr.status == 200){obj.success(xhr.responseText);}else{obj.Error("擷取資料失敗,錯誤代號為:"+xhr.status+"錯誤資訊為:"+xhr.statusText);}}}var html = document.getElementsByTagName("html")[0];html.onclick = function(){ga_ajax({"method" : "post","url" : "dem0o.php","data" : {"name" : "gaga","age" : 10000000,"num" : "12346&598"},"success" : function(data){alert(data);},"Error" : function(text){alert(text);},"async" : false});}