原生ajax
//創建異步對象 var xhr = new XMLHttpRequest(); //設置請求基本信息,並加上請求頭 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.open('post', 'test.php' ); //發送請求 xhr.send('name=Lan&age=18'); xhr.onreadystatechange = function () { // 這步為判斷服務器是否正確響應 if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); } };
jqueryAjax
var loginBtn = document.getElementsByTagName("button")[0]; loginBtn.onclick = function(){ ajax({ type:"post", url:"test.php", data:"name=lan&pwd=123456", success:function(data){ console.log(data); } }); }
fetch
fetch('http://www.mozotech.cn/bangbang/index/user/login', { method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams([ ["username", "Lan"],["password", "123456"] ]).toString() }) .then(res => { console.log(res); return res.text(); }) .then(data => { console.log(data); })
axios
axios({ method: 'post', url: '/abc/login', data: { userName: 'Lan', password: '123' } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
同時發起多個請求:

對比
-
幾種方式的對比
ajax:
【優點:局部更新;原生支持】
【缺點:可能破壞瀏覽器后退功能;嵌套回調】
jqueryAjax:
【在原生的ajax的基礎上進行了封裝;支持jsonp】
fetch:
【優點:解決回調地獄】
【缺點:API 偏底層,需要封裝;默認不帶Cookie,需要手動添加; 瀏覽器支持情況不是很友好,需要第三方的ployfill】
axios:
【幾乎完美】 -
axios
的特點
支持瀏覽器和node.js
支持promise
能攔截請求和響應
能轉換請求和響應數據
能取消請求
自動轉換JSON數據
瀏覽器端支持防止CSRF(跨站請求偽造)
作者:豆漿牛奶寶寶
鏈接:https://www.jianshu.com/p/d771bbc61dab
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。