使用表单提交一个get请求
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>
<input type="text" id="username">
</p>
<p>
<input type="text" id="password">
</p>
<p>
<input type="button" value="提交" id="btn">
</p>
<script>
var btn = document.getElementById('btn')
var username = document.getElementById('username')
var password = document.getElementById('password')
btn.onclick = function() {
var usernameValue = username.value
var passwordvalue = password.value
// 拼接请求参数
var params = 'username=' + usernameValue + '&password=' + passwordvalue
var xhr = new XMLHttpRequest()
xhr.open('get', 'http://127.0.0.1:3000/parameter?' + params)
xhr.send()
xhr.onload = function() {
console.log(xhr.responseText)
console.log(typeof xhr.responseText)
console.log(typeof JSON.parse(xhr.responseText))
}
}
</script>
</body>
</html>
js服务器
var express = require('express')
var path = require('path'))
var app = express()
app.use(express.static(path.join(__dirname, 'public')))
app.get('/parameter', function(req, res) {
res.send(req.query)
})
app.listen(3000, function() {
console.log('app is runing...')
})
注意事项
1、请求参数拼接
get请求方法传递参数需要拼接后,在open方法的地址中传递
2、json数据
json数据在传递时会被转化成字符串,如果想要使用,需要通过JSON.parse()方法将json类型的字符串转化为json类型的对象。