Ajax总结
一、基本使用
示例:基本js文件
//1.引入express
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则
app.get('/',(request,response)=>{
response.send("Hello");
});
//4.启动监听器
app.listen(8000,()=>{
console.log("stat!");
});
示例:服务启动方式
//1.安装nodejs;
//2.创建项目文件夹,使用vscode打开文件夹
//3.在vscode中建立js文件HTML文件和其他文件夹
//4.在最外侧文件夹打开运行终端,输入代码如下
npm init --yes
//5.引入express,代码如下
npm i -g express
//6.启动js服务
node 你建立的js文件名称.js
二、原生Ajax
1.Get请求
html代码如下(示例):
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"
<title>测试</title>
<style>
#result{
width: 200px;
height: 200px;
border:solid 1px deeppink;
}
</style>
</head>
<body>
<button>send</button>
<div id="result"></div>
<script>
//获取butten元素
const btn = document.getElementsByTagName("button")[0];
const result = document.getElementById('result');
//绑定事件
btn.onclick = function(){
// console.log('test');
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化 设置请求方法和url
xhr.open('GET','http://127.0.0.1:8000/server');
//3.发送
xhr.send();
//4.事件绑定 处理服务返回结果
xhr.onreadystatechange = function(){
//判断所有状态
if(xhr.readyState === 4){
//处理成功结果
if(xhr.status >= 200 && xhr.status < 300){
// console.log('success');
result.innerHTML = xhr.response;
}
}
};
}
</script>
</body>
</html>
js中添加代码如下(示例):
const axios = require('axios');
app.get('/server',(request,response)=>{
//响应头 设置允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
//响应体
response.send("Hello");
});
2.Post请求
html代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"
<title>测试</title>
<style>
#result{
width: 200px;
height: 200px;
border:solid 1px deeppink;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
const result = document.getElementById('result');
result.addEventListener("mouseover",function(){
// console.log('success');
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化
xhr.open('POST','http://127.0.0.1:8000/server1');
//3.发送
xhr.send();
//4.处理
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
result.innerHTML = xhr.response;
}
}
}
});
</script>
</body>
</html>
js中添加代码如下(示例):
app.post('/server1',(request,response)=>{
response.setHeader("Access-Control-Allow-Origin","*");
response.send('Hello');
});
3.JSON转换
html代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"
<title>测试</title>
<style>
#result{
width: 200px;
height: 200px;
border:solid 1px deeppink;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
const result = document.getElementById('result');
window.onkeydown = function(){
// console.log('test');
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
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){
// console.log(xhr.response);
// result.innerHTML = xhr.response;
//手动转换JSON
// let data = JSON.parse(xhr.response);
// result.innerHTML = data.name;
// console.log(data);
//自动转换
result.innerHTML = xhr.response.name;
console.log(xhr.response);
}
}
}
};
</script>
</body>
</html>
js中添加代码如下(示例):
app.all('/json-server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
// response.send('Hello');
const data = {
'name':'lili'
};
let str = JSON.stringify(data);
response.send(str);
});
4.IE缓存问题
IE浏览器在重复发送网页上某一个请求时,会优先从本地缓存中调取。
解决方法:
在XMLHttpRequest对象的open方法的url属性后拼接 +’/ie?’+Date.now()
5.请求超时处理
html代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"
<title>测试</title>
<style>
#result{
width: 200px;
height: 200px;
border:solid 1px deeppink;
}
</style>
</head>
<body>
<button>send</button>
<div id="result"></div>
<script>
//获取butten元素
const btn = document.getElementsByTagName("button")[0];
const result = document.getElementById('result');
//绑定事件
btn.onclick = function(){
// console.log('test');
//1.创建对象
const xhr = new XMLHttpRequest();
//超时设置 2s
xhr.timeout = '2000';
//超时回调
xhr.ontimeout = function(){
alert('请求超时');
};
//网路异常处理
xhr.onerror = function(){
alert('网络异常');
};
//2.初始化 设置请求方法和url
xhr.open('GET','http://127.0.0.1:8000/overtime');
//3.发送
xhr.send();
//4.事件绑定 处理服务返回结果
xhr.onreadystatechange = function(){
//判断所有状态
if(xhr.readyState === 4){
//处理成功结果
if(xhr.status >= 200 && xhr.status < 300){
// console.log('success');
result.innerHTML = xhr.response;
}
}
};
}
</script>
</body>
</html>
js中添加代码如下(示例):
app.get('/overtime',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
setTimeout(()=>{
response.send('Hello')
},3000);
});
6.取消请求
html代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"
<title>测试</title>
<style>
#result{
width: 200px;
height: 200px;
border:solid 1px deeppink;
}
</style>
</head>
<body>
<button>点击发送</button>
<button>点击取消</button>
<script>
const btns = document.querySelectorAll('button');
let xhr = null;
btns[0].onclick = function(){
xhr = new XMLHttpRequest();
xhr.open('GET','http://127.0.0.1:8000/overtime');
xhr.send();
};
btns[1].onclick = function(){
//取消请求
xhr.abort();
};
</script>
</body>
</html>
7.重复请求
多次重复请求会占用资源,我们只需要最新的请求即可
html代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"
<title>测试</title>
<style>
#result{
width: 200px;
height: 200px;
border:solid 1px deeppink;
}
</style>
</head>
<body>
<button>点击发送</button>
<script>
const btns = document.querySelectorAll('button');
let xhr = null;
//标志
let flage = false;//是否正在发送ajax请求
btns[0].onclick = function(){
if(flage) xhr.abort();
xhr = new XMLHttpRequest();
flage = true;
xhr.open('GET','http://127.0.0.1:8000/overtime');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
flage = false;
}
};
};
</script>
</body>
</html>
三、使用Jquery发送ajax请求
html代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"
<title>测试</title>
//引入bootstart模板
<link crossorigin="anonymous" rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
//引入jQuery
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2 class="page-header">JQuery发送AJAX请求</h2>
<button class="btn btn-primary">GET</button>
<button class="btn btn-danger">POST</button>
<button class="btn btn-info">通用型方法ajax</button>
<input type="text" class="form-control" disabled>
</div>
<script>
$('button').eq(0).click(function(){
$.get('http://127.0.0.1:8000/jquery-server',{a:100,b:200},function(data){
console.log(data);
},'json');
});
$('button').eq(1).click(function(){
$.post('http://127.0.0.1:8000/jquery-server',{a:100,b:200},function(data){
console.log(data);
},'json');
});
$('button').eq(2).click(function(){
$.ajax({
//url
url: 'http://127.0.0.1:8000/overtime',
//参数
data: {a:100,b:200},
//响应体类型
dataType: 'json',
//请求类型
type: 'GET',
//响应成功的回调
success: function(data){
console.log(data);
},
error: function(){
alert('别看了');
},
timeout: 2000
});
});
</script>
</body>
</html>
js中添加代码如下(示例):
app.all('/jquery-server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
// response.send('Hello');
const data = {
'name':'lili'
};
let str = JSON.stringify(data);
response.send(str);
});
四、Axios发送Ajax请求
html代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"
<title>测试</title>
<link crossorigin="anonymous" rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/js/bootstrap.min.js"></script>
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
</head>
<body>
<button class="btn btn-primary">GET</button>
<button class="btn btn-danger">POST</button>
<button class="btn btn-info">ajax</button>
<script>
//公共url
axios.defaults.baseURL= 'http://127.0.0.1:8000';
const button = document.querySelectorAll('button');
button[0].onclick = function(){
axios.get('/axios-server', {
params: {
id:0
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
})
};
button[1].onclick = function(){
axios.post('/axios-server', {username:100,pass:200},{
params: {
id:0
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
})
};
button[2].onclick = function(){
axios({
method:'post',
url: '/axios-server',
data: {
id:'/axios-server'
},
params: {
a:100,
b:200
},
headers: {
h:100
},
}).then((response)=>{
console.log(response);
})
};
</script>
</body>
</html>
js中添加代码如下(示例):
app.all('/axios-server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
response.send('Hello');
});
五、fetch函数发送Ajax请求
html代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"
<title>测试</title>
</head>
<body>
<button>测试</button>
<script>
//获取butten元素
const btn = document.getElementsByTagName("button")[0];
btn.onclick = function(){
fetch('http://127.0.0.1:8000/fetch-server',{
method: 'POST',
headers: {
a:100
},
body: 'a=100&b=200'
}).then((res)=>{
// console.log(res);
return res.text();
// return res.json();
}).then((res)=>{
console.log(res);
});
};
</script>
</body>
</html>
js中添加代码如下(示例):
app.all('/fetch-server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
response.send('Hello');
});
6、JSONP发送Ajax请求
1.非官方版JSONP
原理:获取自动生成的callback函数名,使用callback函数
html代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"
<title>测试</title>
<link crossorigin="anonymous" rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/js/bootstrap.min.js"></script>
<style>
#result{
width: 200px;
height: 300px;
border: solid 10px pink;
}
</style>
</head>
<body>
<!-- <input type="button" name="获取" id="button" class="btn btn-primary"> -->
<button class="btn btn-primary">获取</button>
<div id="result"></div>
<script>
$('button').eq(0).click(function(){
$.getJSON('http://127.0.0.1:8000/jquery-jsonp-server?callback=?',function(response){
$('#result').html(`
名称:${response.name}<br>
CODE:${response.code}
`);
console.log(response);
});
});
</script>
</body>
</html>
js中添加代码如下(示例):
app.all('/jquery-jsonp-server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
// response.send('Hello');
const data = {
name:'ll',
code:['1','2','3']
}
let str = JSON.stringify(data);
let callback = request.query.callback;
// response.send(str);
response.end(`${callback}(${str})`);
});
2.官方JSONP(cors)
html代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"
<title>测试</title>
<link crossorigin="anonymous" rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/js/bootstrap.min.js"></script>
<style>
#result{
width: 200px;
height: 100px;
border: solid 10px pink;
}
</style>
</head>
<body>
<button class="btn btn-primary">获取</button>
<div id="result"></div>
<script>
const btn = document.querySelector('button');
const result = document.getElementById('result');
btn.onclick = function(){
const xhr = new XMLHttpRequest();
xhr.open('get','http://127.0.0.1:8000/cors-server');
xhr.send();
xhr.onreadystatechange = ()=>{
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
console.log(xhr.response);
}
}
};
};
</script>
</body>
</html>
js中添加代码如下(示例):
app.all('/cors-server',(request,response)=>{
//响应头 设置允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
//响应体
response.send("Hello");
});
完整server.js代码
//1.引入express
const express = require('express');
const axios = require('axios');
const { json } = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则
app.get('/server',(request,response)=>{
//响应头 设置允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
//响应体
response.send("Hello");
});
app.post('/server1',(request,response)=>{
response.setHeader("Access-Control-Allow-Origin","*");
response.send('Hello');
});
app.all('/json-server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
// response.send('Hello');
const data = {
'name':'lili'
};
let str = JSON.stringify(data);
response.send(str);
});
app.get('/ie',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
response.send('IE');
});
app.get('/overtime',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
setTimeout(()=>{
response.send('Hello')
},3000);
});
app.all('/jquery-server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
// response.send('Hello');
const data = {
'name':'lili'
};
let str = JSON.stringify(data);
response.send(str);
});
app.all('/axios-server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
response.send('Hello');
});
app.all('/fetch-server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
response.send('Hello');
});
app.all('/jquery-jsonp-server',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
// response.send('Hello');
const data = {
name:'ll',
code:['1','2','3']
}
let str = JSON.stringify(data);
let callback = request.query.callback;
// response.send(str);
response.end(`${callback}(${str})`);
});
app.all('/cors-server',(request,response)=>{
//响应头 设置允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
//响应体
response.send("Hello");
});
//4.启动监听器
app.listen(8000,()=>{
console.log("start!");
});