本篇文章為大家展示了使用JavaScript怎么對ajax進行封裝,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
function ajax(options) { options = options || {}; options.type = (options.type || "GET").toUpperCase(); options.dataType = options.dataType || "json"; var params = formatParams(options.data); //創建xhr對象 - 非IE6 if (window.XMLHttpRequest) { var xhr = new XMLHttpRequest(); } else { //IE6及其以下版本瀏覽器 var xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //GET POST 兩種請求方式 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); } //接收 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status >= 200 && status < 300) { options.success && options.success(xhr.responseText); } else { options.fail && options.fail(status); } } } } //格式化參數 function formatParams(data) { var arr = []; for (var name in data) { arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name])); } arr.push(("v=" + Math.random()).replace(".","")); return arr.join("&"); }
調用方法
ajax({ url: "data.json", type: "GET", data: {}, dataType: "json", success: function (response) { // 此處放成功后執行的代碼 // 解析返回的字符串 轉為json對象 var usingdata = eval("("+response+")").data; } fail: function (status) { // 此處放失敗后執行的代碼 } });
上述內容就是使用JavaScript怎么對ajax進行封裝,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。