
传统的表单内容会变成请求参数,自动拼接到对应的位置。get会放在请求地址的后面,post会放在请求体当中。
但是在Ajax中, 我们需要自己拼接请求参数,然后根据请求参数的不同,将请求参数放置在不同的位置。

路由:
app.get('/get',(req,res)=>{res.send(req.query)
})
html文件:
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title></head><body><p><input type="text" id="username" /></p><p><input type="text" id="age" /></p><p><input type="button" value="提交" id="btn"></p><script type="text/javascript">var btn=document.getElementById("btn")var username=document.getElementById('username')var age=document.getElementById('age')btn.onclick=function(){var xhr=new XMLHttpRequest()var nameValue=username.valuevar ageValue=age.value//手动拼接请求参数var params='username='+ nameValue +'&age='+ageValuexhr.open('get','http://localhost:3000/get?'+params)xhr.send()xhr.onload=function(){console.log(xhr.responseText)}}</script></body>
</html>
重点在这几句代码:
//手动拼接请求参数var params='username='+ nameValue +'&age='+ageValuexhr.open('get','http://localhost:3000/get?'+params)xhr.send()xhr.onload=function(){console.log(xhr.responseText)}
先是在客户端填写好相关信息:

然后获取这些信息,手动拼接路径,设置ajax传递的服务器地址(带上这个拼接好的带参数的地址)
通过ajax传递给服务器
var params='username='+ nameValue +'&age='+ageValuexhr.open('get','http://localhost:3000/get?'+params)xhr.send()
服务器通过对应的路由,接收对应的请求:并通过express处理参数成字符串,存储在req.query中。
app.get('/get',(req,res)=>{res.send(req.query)
})
然后利用res.send()将响应存储在ajax对象xhr的responseText属性里面:
最后ajax接收到服务器的响应,就会调用下面这个函数,将responseText属性里面的值打印出来。
xhr.onload=function(){console.log(xhr.responseText)}

















