get和post在HTTP中都代表着請求數據,其中get請求相對來說更簡單、快速,效率高些。
get對於請求數據和靜態資源(HTML頁面和圖片),在低版本瀏覽器下都會緩存。高版本瀏覽器只緩存靜態資源,不緩存數據
post從服務器端推送數據(給的多,拿得少),而get是從服務器獲取數據(給的少,拿得多)
post請求包含跟多的請求頭,所以速度沒有get快
post在真正接受數據之前會先將請求頭發送給服務器進行確認,然后才真正發送數據
get請求方式
btn.onclick = function(){ let xhr = new XMLHttpRequest; xhr.open('get','/get?ren='+encodeURI(txt.value),true);// // 其中url里面get是后端給的,?后面user是前后端定義的(或者后端提供) xhr.onload = function(){ console.log(xhr.responseText); } xhr.send(); }
post請求方式
btn.onclick = function(){ let xhr = new XMLHttpRequest; xhr.open('post','/post',true); //設置頭信息 xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); xhr.onload = function(){ console.log(JSON.parse(xhr.responseText)); } xhr.send('user'+txt.value); }
兩者區別
1、get比post速度塊
2、get相對post安全性低
3、get有緩存,post沒有
4、get的url參數可見,post不可見
5、get請求參數會保留歷史記錄,post中參數不會保留
6、get請求數據放在url,post數據在http包體(requrest body)內
7、get只接受ASCII字符的參數數據類型,post沒有限制
8、get會被瀏覽器主動catch,post不會,需要手動設置
9、get在瀏覽器回退時無害,post會再次提交請求
10、get體積小(url字節長度每個瀏覽器不一樣),post可以無限大(根據php.ini 配置文件設定)