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

 1 //引入express框架
 2 const express=require('express')
 3 
 4 //引入路径处理模块
 5 const path=require('path')
 6 
 7 //创建web服务器
 8 const app=express();
 9 
10 //静态资源访问服务器功能
11 app.use(express.static(path.join(__dirname,'public')))
12 
13 //对应03传递get请求参数.html
14 app.get('/get',(req,res)=>{
15     res.send(req.query);
16 })
17 
18 //监听端口
19 app.listen(3000);
20 
21 //控制台提示输出
22 console.log('服务器启动成功3')

猜你喜欢

转载自www.cnblogs.com/technicist/p/12740295.html