一:ajax的请求
1、ajax发送get请求(带参数)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>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>
let username = document.getElementById("username")
let age = document.getElementById("age")
let btn = document.getElementById("btn")
btn.onclick = function () {
let xhr = new XMLHttpRequest()
let usernameValue = username.value
let ageValue = age.value
let params = `username=${usernameValue}&age=${ageValue}`
xhr.open("get",'http://localhost:3000/get?'+params)
xhr.send()
xhr.onload = function () {
console.log( JSON.parse(xhr.responseText) )
}
}
</script>
</body>
</html>
2、ajax发送post请求 ( 带参数 )
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>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>
let username = document.getElementById("username")
let age = document.getElementById("age")
let btn = document.getElementById("btn")
btn.onclick = function () {
let xhr = new XMLHttpRequest()
xhr.open('post','http://localhost:3000/post')
let usernameValue = username.value
let ageValue = age.value
let params = `{username:${usernameValue},age:${ageValue}}`
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(params)
xhr.onload = function () {
console.log(xhr.responseText)
}
}
</script>
</body>
</html>