<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>原生JS模擬JQuery封裝Ajax</title> <script src="./mock-min.js"></script> </head> <body> <button id="btn">異步發送請求</button> <p id="oP"></p> <script> btn.onclick = function(){ ajax(data); } // data做爲參數傳入咱們下面封裝的函數 let data = { type: 'get', //數據 data: { user: "xiejie", pass: '123456', age: 18, }, //回調函數 success: function (data) { console.log(data); document.getElementById('oP').innerHTML = data; }, error:function(err){ console.log(err); }, // 異步發送請求 async: true, // 發送請求的url url: 'getStudent' } // 輔助函數,把傳進來的對象拼接成url的字符串 function toData(obj) { if (obj === null) { return obj; } let arr = []; for (let i in obj) { let str = i + "=" + obj[i]; arr.push(str); } return arr.join("&"); } // 封裝Ajax function ajax(obj) { //指定提交方式的默認值 obj.type = obj.type || "get"; //設置是否異步,默認爲true(異步) obj.async = obj.async || true; //設置數據的默認值 obj.data = obj.data || null; // 根據不一樣的瀏覽器建立XHR對象 let xhr = null; if (window.XMLHttpRequest) { // 非IE瀏覽器 xhr = new XMLHttpRequest(); } else { // IE瀏覽器 xhr = new ActiveXObject("Microsoft.XMLHTTP"); } // 區分get和post,發送HTTP請求 if (obj.type === "post") { xhr.open(obj.type, obj.url, obj.async); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); let data = toData(obj.data); xhr.send(data); } else { //get test.php?xx=xx&aa=xx let url = obj.url + "?" + toData(obj.data); xhr.open(obj.type, url, obj.async); xhr.send(); } // 接收返回過來的數據 xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) { if (obj.success) { obj.success(xhr.responseText); } } else { if (obj.error) { obj.error(xhr.status); } } } } } // 接下來咱們使用Mock來截取Ajax請求 Mock.mock(/getStudent/, 'get', function () { return data.data; }); </script> </body> </html>