继续上一篇笔记接着做
想要在点击按钮时向服务端发送请求
先给按钮绑定单击事件
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
$("button").click(()=>{
})
</script>
之后对其进行ajax操作
可以先分为四步
1.创建对象
const xhr=new XMLHttpRequest();
2.初始化 设置请求方法为get请求和设置URL
xhr.open("GET","http://127.0.0.1:8000/server");
3.发送
xhr.send();
4.事件绑定 处理服务器返回的结果
xhr.onreadystatechange=()=>{
}
PS:将 onreadystatechange 拆分理解
—— on 当....的时候
—— readystate:是 xhr 对象中的属性,表示状态,有五个值:0,1,2,3,4,
0表示未初始化,最开始这个属性的值就是0
1表示open方法已经调用完毕
2表示send方法已经调用完毕
3表示服务端返回的部分结果
4表示服务端返回的所有结果
——change 改变
【在这里 readystate 的五个值会触发四次,每改变一次触发一次,0—>1—>2—>3—>4共四次】
状态为 0 的时候不能处理服务器返回的结果,因为压根就没发请求,自然也没有结果
最适合的是状态为 4 的时候处理,因为当 4 的时候所有结果都已经全部返回
所以,这里要进行一个判断,服务器是否返回了所有结果
xhr.onreadystatechange=()=>{
if(xhr.readyState ==4){
}
}
在这其中还需要判断响应状态码
当状态码为 200 时,才能正确拿到服务端返回的结果
【PS:并非必须是200,只要2开头的都行】
因此,向里面添加 if(xhr.status>=200 && xhr.status<300) 判断
xhr.onreadystatechange=()=>{
if(xhr.readyState ==4){
if(xhr.status>=200 && xhr.status<300){
}else{
}
}
}
当判断成功以后,就处理服务端响应结果
服务端响应结果即为“响应报文”
其分为:行 头 空行 体
在这里只需要拿数据,空行没有什么特殊的意义
接下来就获取 行 头 体 里面的内容
—— 响应行中包括三段内容(协议版本,状态码,状态字符串)
这里只需要状态码和状态字符串
xhr.onreadystatechange=()=>{
if(xhr.readyState ==4){
if(xhr.status>=200 && xhr.status<300){
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr.getAllResponseHeaders());
console.log(xhr.response);
}else{
}
}
}
四个 log 分别打印:状态码 状态字符串 所有响应头 响应体
至此,我们就可以拿到响应的结果了
———————————————————————————————————————————全部代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Access-Control-Allow-Origin" content="127.0.0.1:8000/server">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box{
width: 300px;
height: 300px;
border: 3px solid purple;
}
</style>
</head>
<body>
<button>click</button>
<div id="box"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
$("button").click(()=>{
const xhr=new XMLHttpRequest();
xhr.open("GET","http://127.0.0.1:8000/server");
xhr.send();
xhr.onreadystatechange=()=>{
if(xhr.readyState ==4){
if(xhr.status>=200 && xhr.status<300){
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr.getAllResponseHeaders());
console.log(xhr.response);
// $("#box").html(xhr.response);
}else{
}
}
}
})
</script>
</body>
</html>
var cd=require('express');
var ex=cd();
ex.get('/server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.send("hello");
})
ex.listen(8000,()=>{
console.log("服务已启动");
})