Ajax--向服务器传递get请求参数


请求参数传递
传统网站表单提交
<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);  })


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM