原生ajax請求
阿新 • • 發佈:2017-09-29
.ajax pre 請求 amp open logs stat send read
原生ajax請求:
// ajax四步:創建XMLHttpRequest對象,連接服務器,發送請求,接收響應數據 ajax: function (options) { options = options || {}; options.type = (options.type || "GET").toUpperCase(); options.dataType = options.dataType || ‘json‘; var xhr = new XMLHttpRequest(); var arr = []; if (options.params) { for (var key in options.params) { arr.push(encodeURIComponent(key) + "=" + encodeURIComponent(options.params[key])) } var postData = arr.join("&") options.url = options.url + "?" + postData } xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status >= 200 && status < 300) { try { options.success && options.success(JSON.parse(xhr.responseText)) } catch (e) { options.success && options.success(xhr.responseText) } } else { options.fail && options.fail(status) } } } if (options.type == "GET") { xhr.open("GET", options.url, true) xhr.send(null) } else if (options.type == "POST") { xhr.open("POST", options.url, true) xhr.setRequestHeader("Content-Type", "application/json") xhr.send(JSON.stringify(options.data)) } },
然後在登錄時候調用,註意這裏要考慮到post傳參和url也傳參的情況,網上大多都沒有處理這種情況!!!
login.ajax({ url: ‘/login‘, type: ‘POST‘, params: { Phone: phone }, success: function (response) { }, fail: function (status) { } })
原生ajax請求