ajax:一種請求數據的方式,不需要刷新整個頁面;
ajax的技術核心是 XMLHttpRequest 對象;
ajax 請求過程:創建 XMLHttpRequest 對象、連接服務器、發送請求、接收響應數據;
下面簡單封裝一個函數,之后稍作解釋
ajax({ url: "./TestXHR.aspx", //請求地址 type: "POST", //請求方式 data: { name: "super", age: 20 }, //請求參數 dataType: "json", success: function (response, xml) { // 此處放成功后執行的代碼 }, fail: function (status) { // 此處放失敗后執行的代碼 } }); function ajax(options) { options = options || {}; options.type = (options.type || "GET").toUpperCase(); options.dataType = options.dataType || "json"; var params = formatParams(options.data); //創建 - 非IE6 - 第一步 if (window.XMLHttpRequest) { var xhr = new XMLHttpRequest(); } else { //IE6及其以下版本瀏覽器 var xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //接收 - 第三步 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status >= 200 && status < 300) { options.success && options.success(xhr.responseText, xhr.responseXML); } else { options.fail && options.fail(status); } } } //連接 和 發送 - 第二步 if (options.type == "GET") { xhr.open("GET", options.url + "?" + params, true); xhr.send(null); } else if (options.type == "POST") { xhr.open("POST", options.url, true); //設置表單提交時的內容類型 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(params); } } //格式化參數 function formatParams(data) { var arr = []; for (var name in data) { arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]