码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2020-04-20 21:19:34      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:color   element   访问   function   onload   back   监听端口   处理模块   提交   

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

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

标签:color   element   访问   function   onload   back   监听端口   处理模块   提交   

原文地址:https://www.cnblogs.com/technicist/p/12740295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!