Ajax学习笔记
一、关于Ajax
什么是Ajax?
Ajax全称为Asynchronous JavaScript And XML ,就是异步的JS和XML。通过AJAX可以在浏览器中向服务器发送异步请求,最大的优势:无需刷新页面获取数据。
AJAX不是新的编程语言,而是一种将现有的标准组合在一起使用的新方式。
什么是XML?
XML是可扩展标记语言。被设计用来传输和存储数据。
XML和HTML相似。不同的是HTML用来呈现数据,而XML用来传输和存储数据。HTML中都是预定义标签,而XML中没有预定义标签,全都是自定义标签,用来表示一些数据。
优缺点
优点:
1、可以无需刷新页面与服务器端进行通信。
2、允许根据用户事件来更新部分页面内容。
缺点:
1、没有浏览历史,不能回退
2、存在跨域问题(同源)
3、不利于SEO(爬虫)
二、HTTP协议
HTTP协议(超文本传输协议):协议详细规定了浏览器和万维网服务器之间互相通信的规则。
HTTP协议报文
分为请求报文和响应报文:
请求报文:
行: POST /s?ie=utf-8 HTTP/1.1
头:Host: baidu.com
Cookie: name=zhoushen
Cotent-type: application/x-www-from-urlencoded
User-Agent: chrome 83
空行:
体:username=admin&password=admin
响应报文:
行:HTTP/1.1 200(状态码) OK
头:Cotent-type: text/html;charset=utf-8
Cotent-length: 2048
Cotent-encoding: gzip
空行:
响应体:响应体内放的是html的内容
三、AJAX操作
AJAX的基本操作
//引入express
const { request } = require('express');
const express=require('express');
//创建应用对象
const app=express();
//创建路由规则
//request 是对请求报文的封装
//response 是对响应报文的封装
app.get('/',(request,response)=>{
//设置响应头,设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//设置响应
response.send('HELLO EXPRESS');
});
//监听端口启动服务
app.listen(8000,()=>{
console.log("服务器已经启动,8000 端口监听中")
})
AJAX的请求操作
发送GET请求
//创建对象
const xhr=new XMLHttpRequest();
//初始化 设置请求方法和url
xhr.open('GET','http://127.0.0.1:8000/server');
//发送
xhr.send();
//事件绑定
xhr.onreadystatechange=function(){
//判断(服务端返回了所有的结果)
if(xhr.readyState === 4){
//判断响应状态码: 200 404 403 401 500
if(xhr.status === 200 && xhr.status < 300){
//处理结果
console.log(xhr.status);//状态码
console.log(xhr.statusText);//状态字符串
console.log(xhr.getAllResponseHeaders());//所有响应头
console.log(xhr.response);//响应体
}
else{
}
}
}
发送POST请求
//创建对象
const xhr=new XMLHttpRequest();
//初始化 设置请求方法和url
xhr.open('POST','http://127.0.0.1:8000/server');
//发送
xhr.send('a=1&b=2');//可以向里面传参数
//事件绑定
xhr.onreadystatechange=function(){
//判断(服务端返回了所有的结果)
if(xhr.readyState === 4){
//判断响应状态码: 200 404 403 401 500
if(xhr.status === 200 && xhr.status < 300){
//处理服务端返回的结果
result.innerHTML = xhr.response;
}
else{
}
}
}
设置请求头信息
const xhr=new XMLHttpRequest();
xhr.open('POST','http://127.0.0.1:8000/server');
//设置请求头信息
xhr.setRequestHeader('Cotent-Type','application/x-www-form-urlencoded');
xhr.send('a=1&b=2');
xhr.onreadystatechange=function(){
if(xhr.readyState === 4){
if(xhr.status === 200 && xhr.status < 300){
result.innerHTML = xhr.response;
}
else{
}
}
}
服务端响应JSON数据
自动转换:
const xhr=new XMLHttpRequest();
//设置响应体数据类型
xhr.responseType='json';
xhr.open('GET','http://127.0.0.1:8000/server');
xhr.setRequestHeader('Cotent-Type','application/x-www-form-urlencoded');
xhr.send('a=1&b=2');
xhr.onreadystatechange=function(){
if(xhr.readyState === 4){
if(xhr.status === 200 && xhr.status < 300){
result.innerHTML = xhr.response.name;//获取数据
}
}
}
解决IE缓存问题
const xhr=new XMLHttpRequest();
//解决ie缓存的问题
xhr.open('GET','http://127.0.0.1:8000/ie?t='+Date.now());
xhr.send('a=1&b=2');
xhr.onreadystatechange=function(){
if(xhr.readyState === 4){
if(xhr.status === 200 && xhr.status < 300){
result.innerHTML = xhr.response.name;//获取数据
}
}
}
请求超时和网络异常
解决请求超时和网络异常:
const xhr=new XMLHttpRequest();
//超时设置 规定超过2秒
xhr.timeout=2000;
//超时回调
xhr.ontimeout=function(){
alert("网络异常,请稍后重试");
}
//网络异常回调
xhr.onerror=function(){
alert("你的网络似乎出了一些问题");
}
xhr.open('GET','http://127.0.0.1:8000/delay);
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState === 4){
if(xhr.status === 200 && xhr.status < 300){
result.innerHTML = xhr.response.name;//获取数据
}
}
}
AJAX请求取消
使用abort()方法即可取消AJAX请求:
xhr.abort();
解决请求重复问题
let xhr=null;
let isSending=false;//是否正在发送AJAX请求
if(isSending) xhr.abort();//如果正在发送,则取消发送该请求
xhr=new XMLHttpRequest();
isSending=true;//修改标识变量的值
xhr.open('GET','http://127.0.0.1:8000/delay);
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState === 4){
isSending=false;//修改标识变量
}
}
四、跨域
同源策略
同源策略是浏览器的一种安全策略。
同源:协议、域名、端口号必须完全相同。
跨域:违背同源策略就是跨域。
jsonp
jsonp:是一个非官方的跨域解决方案,只支持get请求。
工作方式:在网页中有一些标签天生具有跨域能力。如img、link、iframe、script。JSONP就是利用script标签跨域能力来发送请求的。
CORS
CORS:跨域资源共享,CORS是官方的跨域解决方案,它的特点是不需要在客户端做任何特殊的操作,完全在服务器中进行处理,支持get和post请求。跨域资源共享标准新增了一组HTTP首部字段,允许服务器声明哪些源站通过浏览器有权限访问哪些资源。
工作方式:CORS是通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应以后就会对响应放行。