Ajax的使用,axios发送ajax请求,jquery发送ajax请求
AJAX 简介
AJAX 全称为 Asynchronous JavaScript And XML,就是异步的 JS 和 XML。
通过 AJAX 可以在浏览器中向服务器发送异步请求,最大的优势:无刷新获取数据。
AJAX 不是新的编程语言,而是一种将现有的标准组合在一起使用的新方式。
XML 简介
XML 可扩展标记语言。
XML 被设计用来传输和存储数据。
XML 和 HTML 类似,不同的是 HTML 中都是预定义标签,而 XML 中没有预定义标签,
全都是自定义标签,用来表示一些数据。
比如说我有一个学生数据:
name = "孙悟空" ; age = 18 ; gender = "男" ;
用 XML 表示:
<student>
<name>孙悟空</name>
<age>18</age>
<gender>男</gender>
</student>
用 JSON 表示:
{"name":"孙悟空","age":18,"gender":"男"}
现在已经被 JSON 取代了
AJAX 的特点
AJAX 的优点
- 可以无需刷新页面而与服务器端进行通信。
- 允许你根据用户事件来更新部分页面内容。
AJAX 的缺点
- 没有浏览历史,不能回退
- 存在跨域问题(同源)
- SEO 不友好
HTTP协议
AJAX 的使用
AJAX 的优点
- 可以无需刷新页面而与服务器端进行通信。
- 允许你根据用户事件来更新部分页面内容。
1.3.2 AJAX 的缺点
- 没有浏览历史,不能回退
- 存在跨域问题(同源)
- SEO 不友好
1.4 AJAX 的使用
1.核心对象
XMLHttpRequest,AJAX 的所有操作都是通过该对象进行的。
2.使用步骤
- 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
- 设置请求信息
xhr.open(method, url);
//可以设置请求头,一般不设置
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
- 发送请求
xhr.send(body) //get 请求不传 body 参数,只有 post 请求使用
- 接收响应
//xhr.responseXML 接收 xml 格式的响应数据
//xhr.responseText 接收文本格式的响应数据
xhr.onreadystatechange = function (){ if(xhr.readyState == 4 && xhr.status == 200){ var text = xhr.responseText; console.log(text);
}}
Express框架的使用
下载Express npm i espress; 前提是下载了node.js
PS D:\study> npm init --yes//初始化npm
Wrote to D:\study\package.json:
{
"name": "study",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
added 50 packages, and audited 51 packages in 8s
2 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
npm notice
npm notice New minor version of npm available! 8.1.2 -> 8.4.0
npm notice Changelog: https://github.com/npm/cli/releases/tag/v8.4.0
npm notice Run npm install -g npm@8.4.0 to update!
npm notice
PS D:\study>
基本使用
//1.引入express
const express =require('express');
//2创建应用对象
const app = express();
//3.创建路由规则
//request 是对请求报文的封装
//response 是对响应报文的封装
app.get('/',(request,response)=>{
//设置响应
response.send('hello word');
});
//4.监听端口启动服务
app.listen(8000,()=>{
console.log("服务已启动, 8000端口监听中");
})
Ajax 基本请操作
先搭建一个服务器
//1.引入express
const { response } = require('express');
const express = require('express');
const { request } = require('http');
//2创建应用对象
const app = express();
//3.创建路由规则
//request 是对请求报文的封装
//response 是对响应报文的封装
app.get('/server', (request, response) => {
//设置响应头 允许跨域 注意字不要写错
// response.setHeader('Access-Control-Allow-Orign', '*');
response.setHeader('Access-Control-Allow-Origin','*')
//设置响应体
response.send('hello AJAX');
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log("服务已启动, 8000端口监听中");
})
后在做前后端交互
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> AJAX CET 请求</title>
<style>
#result {
width: 200px;
height: 200px;
border: 2px solid red;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn = document.getElementsByTagName('button')[0];
btn.onclick = function () {
//创建对象
const xhr = new XMLHttpRequest();
//做初始化 设置请求的方法和url
xhr.open('GET', 'http://localhost:8000/server');
//发送请求
xhr.send();
//事件绑定 处理服务端返回的结果
//readystate 是xhr对象中的属性 表示状态 为0 1 2 3 4
//change 改变
xhr.onreadystatechange = function () {
//判断(服务端返回的结果)
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//处理结果 包括 行 头 空行 体
//响应行
console.log(xhr.status);//状态码
console.log(xhr.statusText);//状态字符串
console.log(xhr.response);//响应体
console.log(xhr.getAllResponseHeaders());//所有响应头
}
}
}
}
</script>
</body>
</html>
Ajax设置请求参数操作(get)
只要在url后面机上加个?请求参数即可
‘http://localhost:8000/server?a=100&b=100’
查看
Ajax发送post请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>post 请求</title>
<style>
.result{
width: 200px;
height: 100px;
border: 1px solid red;
}
</style>
</head>
<body>
<div class="result"></div>
<script>
//获取元素对象
const result=document.querySelector('.result');
result.addEventListener('mouseover',function(){
// console.log('text');
//创建对象
const xhr=new XMLHttpRequest();
//初始化 设置类型与url
xhr.open('POST','http://127.0.0.1:8000/server');
//发送
xhr.send();
//事件绑定
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status>=200&&xhr.status<300){
//处理服务端
result.innerHTML=xhr.response;
}
}
}
})
</script>
</body>
</html>
设置参数
//初始化 设置类型与url
xhr.open('POST','http://127.0.0.1:8000/server');
//发送
xhr.send('a=100&b=100');
//事件绑定
Ajax设置请求头信息
在open后面添加下面代码Content-type(预定义)设置请求体类型
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');//固定写法
设置自定义请求头信息(name)自定义 需要去改服务器 all 因为浏览器会返回一个option请求所以改服务端改为all是为了接收任务请求(接受任何类型发送的请求)
xhr.setRequestHeader('name','lrq')
/response 是对响应报文的封装
app.all('/server', (request, response) => {
//设置响应头 允许跨域
// response.setHeader('Access-Control-Allow-Orign', '*');
response.setHeader('Access-Control-Allow-Origin','*')
//设置响应头
response.setHeader('Access-Control-Allow-Headers','*')//*
//设置响应体
response.send('hello AJAX-post');
});
Ajax服务端响应json数据
app.all('/json-server', (request, response) => {
//设置响应头 允许跨域
// response.setHeader('Access-Control-Allow-Orign', '*');
response.setHeader('Access-Control-Allow-Origin','*')
//设置响应头
response.setHeader('Access-Control-Allow-Headers','*')
//设置响应体
//响应一个数据 json数据
const data={
name: 'lrq'
};
//将对象转换成字符串
let str= JSON.stringify(data);
response.send(str);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.result{
width: 200px;
height: 100px;
border: 1px solid red;
}
</style>
</head>
<body>
<div class="result"></div>
<script>
const result=document.querySelector('.result')
window.onkeydown=function(){
// console.log('text');
//发送请求
const xhr= new XMLHttpRequest();
//设置响应体数据类型 自动转换
xhr.responseType='json'
//初始化 设置类型和url
xhr.open('GET','http://127.0.0.1:8000/json-server')
//发送
xhr.send()
//绑定事件
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status>=200&&xhr.status<300){
// result.innerHTML=xhr.response
// console.log(xhr.response);
//手动转换 json数据
// let data=JSON.parse(xhr.response);
// console.log(data);
console.log(xhr.response);
result.innerHTML=xhr.response.name
}
}
}
}
</script>
</body>
</html>
自动重启工具 nodemon
npm install -g nodemon 下载 nodemon
npx nodemon server.js 启动服务器
Ajax请求超时与网络异常处理
//超时设置
xhr.timeout=2000;
//超时回调
xhr.ontimeout=function(){
alert('网络异常')
}
//网络异常
xhr.onerror=function(){
alert('你的网络出现了问题')
}
Ajax取消请求
调用abort方法取消发送
x.abort();
<button>发送请求</button>
<button>取消请求</button>
<script>
const btns=document.querySelectorAll('button');
let x=null;
btns[0].onclick=function(){
x = new XMLHttpRequest();
x.open('GET','http://127.0.0.1:8000/delay');
x.send();
}
//abort 取消发送
btns[1].onclick=function(){
x.abort();
}
</script>
Ajax请求重复发送问题
<button>发送请求</button>
<script>
const btns = document.querySelectorAll('button');
let x = null;
//加个标识变量
let ispending = false; //判断是否正在发送Ajax请求
btns[0].onclick = function () {
//判断表示变量
if(ispending){
x.abort()//如果正在发送取消上次发送的请求 创建一个新请求
}
//到这里就开始发送
x = new XMLHttpRequest();
//修改标识变量
ispending = true;
x.open('GET', 'http://127.0.0.1:8000/delay');
x.send();
x.onreadystatechange = function () {
if (x.readyState == 4) {
ispending = false;
}
}
}
// //abort 取消发送
// btns[1].onclick = function () {
// x.abort();
// }
</script>
jQuery发送Ajax请求
四个参数 ‘url‘,{ 请求参数},回调函数 ,数据类型
data 相当于xhr.response
通用ajax发送请求
axios发送请求
<script src="[https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js]"></script>
引入即可
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<button>GET</button>
<button>POST</button>
<button>AJAX</button>
<script>
const btns = document.querySelectorAll('button');
btns[0].onclick = function () {
//get 请求
axios.get('http://127.0.0.1:8000/axios-server', {
//url 参数
params: {
id: 100,
vip: 7
},
//请求头信息
headers: {
name: 'lrq'
}
}).then(value => {
console.log(value);
})
}
btns[1].onclick = function () {
axios.post('http://127.0.0.1:8000/axios-server',
//请求体
{
username: 'admin',
password: '123'
}, {
//url
params: {
id: 200,
vip: 3
},
//请求头
headers: {
height: 100,
weight: 100
}
})
}
btns[2].onclick=function(){
axios({
//请求方法
method:'post',
//url
url:'http://127.0.0.1:8000/axios-server',
//url 参数
params:{
id:20,
name:'lrq'
},
//头信息
headers:{
a:100,
b:100
},
//请求体
data:{
usernamee:'lrq',
password:1234
}
})
}
</script>
</body>
</html>
fetch函数发送Ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>ajax 请求</button>
<script>
const btn = document.querySelector('button');
btn.onclick = function () {
fetch('http://127.0.0.1:8000/fetch-server',{
//请求方法
method:'POST',
//请求头
headers:{
name:'lrq'
},
//请求体
body:'username=lrq&password=123'
}).then(response =>{
// return response.json();//返回的是json数据
return response.text()//返回的是字符串
}).then(response =>{
console.log(response);
})
}
</script>
</body>
</html>
跨域
CORS 标准
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
- CORS 是什么?
CORS(Cross-Origin Resource Sharing),跨域资源共享。CORS 是官方的跨域解决方
案,它的特点是不需要在客户端做任何特殊的操作,完全在服务器中进行处理,支持 get 和 post 请求。跨域资源共享标准新增了一组 HTTP 首部字段,允许服务器声明哪些源站通过浏览器有权限访问哪些资源
- CORS 怎么工作的?
CORS 是通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应以后就会对响应放行。
app.all('/cors-server', (request, response) => {
//设置响应头 允许跨域
// response.setHeader('Access-Control-Allow-Orign', '*');
response.setHeader('Access-Control-Allow-Origin', '*')
response.setHeader('Access-Control-Allow-Headers', '*')
response.setHeader('Access-Control-Allow-Method', '*')
//设置响应体
response.send('hello cors')
});