請求參數傳遞
傳統網站表單提交
<form method="get" action="http://www.example.com">
<input type="text" name="username"/>
<input type="password" name="password"/>
</form>
Ajax的GET請求方式
xhr.open('get','http://www.example.com?name=zhangshan&age=20');
a.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <p> 9 <input type="text" id="username" > 10 </p> 11 <p> 12 <input type="text" id="age"> 13 </p> 14 <p> 15 <input type="button" value="提交" id='btn'> 16 </p> 17 <script type="text/javascript"> 18 //獲取按鈕元素 19 var btn=document.getElementById('btn'); 20 //獲取姓名文本框 21 var username=document.getElementById('username'); 22 //獲取年齡文本框 23 var age=document.getElementById('age'); 24 //為按鈕添加點擊事件 25 btn.onclick=function(){ 26 //創建ajax對象 27 var xhr=new XMLHttpRequest(); 28 //獲取用戶在文本框中輸入的值 29 var nameValue=username.value; 30 var ageValue=age.value; 31 32 //alert(nameValue) 33 //alert(ageValue) 34 35 //拼接請求參數 36 var params='username='+nameValue+'&age='+ageValue; 37 38 //配置Ajax對象 39 xhr.open('get','http://localhost:3000/get?'+params); 40 //發送請求 41 xhr.send(); 42 //獲取服務器端響應的數據 43 xhr.onload=function(){ 44 console.log(xhr.responseText) 45 } 46 } 47 </script> 48 </body> 49 </html>
運行截圖:

app.js
//對應03傳遞get請求參數.html app.get('/get',(req,res)=>{ res.send(req.query); })
