一: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>
//ajax发送get请求,带参
let username = document.getElementById("username")
let age = document.getElementById("age")
let btn = document.getElementById("btn")
//按钮被点击时,发送ajax请求
btn.onclick = function () {
let xhr = new XMLHttpRequest()
let usernameValue = username.value
let ageValue = age.value
//拼接上方input输入框中的参数
let params = `username=${usernameValue}&age=${ageValue}`
//格式为username=xx&age=xx
//把参数放在地址的后面
xhr.open("get",'http://localhost:3000/get?'+params)
xhr.send()
xhr.onload = function () {
//将返回的字符串格式json,解析成对象格式
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>
//ajax发送post请求,带参
let username = document.getElementById("username")
let age = document.getElementById("age")
let btn = document.getElementById("btn")
//按钮被点击时,发送ajax请求
btn.onclick = function () {
let xhr = new XMLHttpRequest()
//post请求,地址后面不跟参数
xhr.open('post','http://localhost:3000/post')
let usernameValue = username.value
let ageValue = age.value
//方法一:设置的是username=xx&age=xx这种类型的参数
//拼接post参数
//let params = `username=${usernameValue}&age=${ageValue}`
//post请求,必须设置参数格式类型
//application/x-www-form-urlencoded => username=xx&age=xx 像表单一样提交数据
//xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
//post请求,参数放到send中.
// xhr.send(params)
//方法二:设置的是{username: xxxx, age: xx}
let params = `{username:${usernameValue},age:${ageValue}}`
//post请求,必须设置参数格式类型. 告诉服务器,我等下带的但是是json格式参数
xhr.setRequestHeader('Content-Type', 'application/json')
//因为params是字符串的类型,所以直接放在send里面,如果是对象类型那么就先转换为字符串的类型,xhr.send(JSON.stringify({money: 1000, age: 30}))
//post请求,参数放到send中.
xhr.send(params)
xhr.onload = function () {
console.log(xhr.responseText)
}
}
</script>
</body>
</html>