AJAX
1.AJAX的特点
1.优点
- 可以无需刷新页面而与服务器端进行通信
- 允许你根据用户事件来刷新部分页面内容
2.缺点
- 没有浏览历史,不能回退
- 存在跨域问题
- SEO(搜索引擎优化)不友好 --> 爬虫不可爬取Ajax请求得来的数据
2.HTTP协议
1.http
超文本传输协议,规定了浏览器和万维网服务器之间相互通信的规则
2.请求报文
-
请求行:
- 请求类型:post、delete、put、get四种方式分别对应对数据的增删改查
- URL路径
- HTTP协议版本
-
请求头:
- Host:bilibili.com
- Cookie:name=hgg
- Content-type:application/x-www-form-urlencoded
- User-Agent:Chrome 83
-
请求空行:必须要有
-
请求体
-
如果是get请求,请求体为空
-
如果是post请求,请求体可以不为空 e.g–>username=admin&password=admin
-
3.响应报文
- 响应行:
- HTTP协议版本
- 响应状态码:200、404、403、500、401等
- 响应状态字符串:与状态码对应
- 响应头:
- Content-type:text/html;charset=utf-8
- Content-length:2048
- Content-encoding:gzip
- 响应空行:必须要有
- 响应体:响应的数据内容
3.原生Ajax
1.ajax中的get请求
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button>click</button>
<div class="content"></div>
</body>
<script>
document.querySelector('button').onclick=function(){
let xhr=new XMLHttpRequest();
xhr.open('GET','http://localhost:3000/ajax');
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status>=200&&xhr.status<300){
console.log(xhr)
document.querySelector('.content').innerHTML=xhr.responseText;
}
}
}
}
</script>
</html>
服务器代码
let express=require('express');
let app=express();
app.get('/ajax',(req,res)=>{
res.setHeader('Access-Control-Allow-Origin','*')
res.send('232323')
})
app.listen(3000)
请求结果
2.ajax中的get请求携带参数
后缀在URL之后,用 ? 分割路径与参数键值对,e.g:
xhr.open('GET','http://localhost:3000/ajax?name=2233&pass=cdd');
3.ajax中的post请求
写法与get方式大致相同,变化的地方在于
//前台代码变化
xhr.open('POST','http://localhost:3000/ajax?name=2233&pass=cdd');
//后台代码变化
app.post('/ajax',(req,res)=>{
res.setHeader('Access-Control-Allow-Origin','*')
res.send('232323')
})
传递请求体参数设置在xhr.send中,e.g:
xhr.send('user=333333&agent=chrome');
请求结果
4.设置请求头
xhr中的setRequestHeader方法,接收两个参数,头的名字和头的值,同样可以在network中查看
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
请求结果
5.服务器响应json数据
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button>click</button>
<div class="content"></div>
</body>
<script>
document.querySelector('button').onclick=function(){
let xhr=new XMLHttpRequest();
xhr.open('GET','http://localhost:3000/json');
xhr.responseType='json';//设置响应体类型,将自动进行数据格式的转换
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status>=200&&xhr.status<300){
console.log(xhr)
for (const xhrKey in xhr.response) {
let div=document.createElement('div');
div.innerHTML=`${
xhrKey}------${
xhr.response[xhrKey]}`;
document.body.appendChild(div);
}
}
}
}
}
</script>
</html>
服务器代码
let express