一直在用jQuery方法來寫ajax請求,用的多了,難免對這其中是怎麼實現的產生了興趣,因而乎,小弟閒來無聊研究了一下原生實現ajax請求,網上看了不少前輩們的關於ajax請求的封裝方法,也借鑑了不少經驗,因而乎就出現了小弟的一個原生JS封裝ajax的版本,但願你們看了以後可以明白,下面就是我實現的方法,其中的註釋很清晰,方便你們的理解。ajax
<script>json
/** * 對封裝好的ajax請求進行調用 * */ ajax({ url:"", //請求地址 type:'GET', //請求方式 data:{name:'zhangsan',age :'23',email:'2372734044@qq.com'}, //請求參數 dataType:"json", // 返回值類型的設定 async:false, //是否異步 success:function (response,xml) { console.log(response); // 此處執行請求成功後的代碼 }, fail:function (status) { console.log('狀態碼爲'+status); // 此處爲執行成功後的代碼 } }); function ajax(options) { /** * 傳入方式默認爲對象 * */ options = options || {}; /** * 默認爲GET請求 * */ options.type = (options.type || "GET").toUpperCase(); /** * 返回值類型默認爲json * */ options.dataType = options.dataType || 'json'; /** * 默認爲異步請求 * */ options.async = options.async || true; /** * 對須要傳入的參數的處理 * */ var params = getParams(options.data); var xhr; /** * 建立一個 ajax請求 * W3C標準和IE標準 */ if (window.XMLHttpRequest){ /** * W3C標準 * */ xhr = new XMLHttpRequest(); }else{ /** * IE標準 * @type {ActiveXObject} */ 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 ,options.async); xhr.send(null) }else if (options.type == 'POST'){ /** *打開請求 * */ xhr.open('POST',options.url,options.async); /** * POST請求設置請求頭 * */ xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); /** * 發送請求參數 */ xhr.send(params); } } /** * 對象參數的處理 * @param data * @returns {string} */ function getParams(data) { var arr = []; for (var param in data){ arr.push(encodeURIComponent(param) + '=' +encodeURIComponent(data[param])); } console.log(arr); arr.push(('randomNumber=' + Math.random()).replace('.')); console.log(arr); return arr.join('&'); }</script>app
封裝以上的方法主要是由於原生js傳遞請求參數比較麻煩,因而乎改良了一下,但願對你們有幫助,喜歡個人文章的話,就給我來個喜歡吧,dom
我最喜歡doge了異步