一、 Express 开启服务
前提 :node环境 + 全局下载 express
express官网
1、 express 安装与 基本 使用
npm init --yes
npm i express
node 脚本
2、 server.js
代码 【提供后端服务】
node server.js
开启服务
// 1. 引入express
const express = require('express');
// 2. 创建应用对象
const app = express();
// 3. 创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
app.get('/server', (request, response) => {
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
// 设置响应体
response.send('HELLO AJAX');
});
// 可以接受任意类型的请求
app.all('/json-server', (request, response) => {
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
// 响应头
response.setHeader('Access-Control-Allow-Headers', '*')
// 响应一个数据
const data = {
name: 'ntt'
};
// 对对象进行字符串转换
let str = JSON.stringify(data);
// 设置响应体
response.send(str);
});
// 针对IE缓存
app.get('/ie', (request, response) => {
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
// 设置响应体
response.send('HELLI IE-2');
});
// 延时响应
app.get('/delay', (request, response) => {
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
// 设置响应体
setTimeout(() => {
response.send('延时响应');
}, 3000)
});
// jQuery 服务
app.all('/jQuery-server', (request, response) => {
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
const data = { name: '尚硅谷' };
response.send(JSON.stringify(data));
// response.send('Hello jQuery AJAX');
});
// axios-server
app.all('/axios-server', (request, response) => {
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', '*');
const data = { name: '尚硅谷' };
response.send(JSON.stringify(data));
response.send('Hello axios AJAX');
});
app.all('/fetch-server', (request, response) => {
// 设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', '*');
const data = { name: '尚硅谷' };
response.send(JSON.stringify(data));
response.send('Hello axios AJAX');
});
//4. 监听端口启动服务
app.listen(8080, () => {
console.log("服务已经启动,8080端口监听中...");
})
二、 请求实例
2-1 GET 和 post请求
1、 1-GET.hml
<!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 GET请求</title>
<style>
#result {
width: 200px;
height: 100px;
border: 1px solid #90b;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result">
</div>
<script>
// 获取button元素
const btn = document.getElementsByTagName('button')[0];
// 绑定事件
btn.onclick = function() {
// 1. 创建对象
const xhr = new XMLHttpRequest();
// 2. 初始化设置请求方法和url
// xhr.open('GET', 'http://localhost:8080/server');
// 发送参数
xhr.open('GET', 'http://localhost:8080/server?a=100&b=200&c=300');
// 3. 发送
xhr.send();
// 4. 事件绑定 处理服务端返回的结果
// on when 当..时候
// resdystate 是 xhr 对象中的属性, 表示状态 0 1 2 3 4
// change 改变
xhr.onreadystatechange = function() {
// 判断
if (xhr.readyState === 4) {
// 判断响应状态码 200 404 403 401 500
// 2xx 成功
if (xhr.status >= 200 && xhr.status < 300) {
// 处理结果 行 头 空行 体
// 1. 响应行
console.log(xhr.status); // 状态码
console.log(xhr.statusText); // 状态字符串
console.log(xhr.getAllResponseHeaders());
console.log(xhr.response); // 响应体
result.innerHTML = xhr.response;
}
}
}
}
</script>
</body>
</html>
2、 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 #903;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
// 获取元素对象
const result = document.getElementById("result");
// 绑定事件
result.addEventListener("mouseover", function() {
// console.log("test");
// 1. 创建对象
const xhr = new XMLHttpRequest();
// 2. 初始化 设置类型 与 URL
xhr.open('POST', 'http://localhost:8080/server');
// 设置请求头
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.setRequestHeader('name', 'niutt');
// 3. 发送
// xhr.send();
xhr.send('a=100&b=200&c=300');
xhr.send('a:100&b:200&c:300');
// 4. 事件绑定
xhr.onreadystatechange = function() {
// 判断
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
// 处理服务器返回的结果
result.innerHTML = xhr.response;
}
}
}
})
</script>
</body>
</html>
2-2 AJAX 取消请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>取消请求</title>
</head>
<body>
<button>点击发送</button>
<button>单击取消</button>
<script>
// 获取元素对象
const btns = document.querySelectorAll('button');
let x = null;
btns[0].onclick = function() {
x = new XMLHttpRequest();
x.open("GET", "http://localhost:8080/delay");
x.send();
}
// 取消请求 abort
btns[1].onclick = function() {
x.abort();
}
</script>
</body>
2-3 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>点击发送</button>
<script>
// 获取元素对象
const btns = document.querySelectorAll('button');
let x = null;
// 标识变量
let isSending = false; // 是否正在发送ajax请求
btns[0].onclick = function() {
// 判断标识变量
if (isSending) x.abort(); // 如果正在发送,则取消该请请求,创建一个新的请求
x = new XMLHttpRequest();
// 修改 标识变量的值
isSending = true;
x.open("GET", 'http://localhost:8080/delay');
x.send();
x.onreadystatechange = function() {
if (x.readyState === 4) {
//请求完成, 修改标识变量
isSending = false;
}
}
}
// abort
btns[1].onclick = function() {
x.abort();
}
</script>
</body>
</html>
2-4 JSON请求
<!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 #903;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
// 绑定键盘按下事件
window.onkeydown = function() {
// console.log('test');
// 发送请求
const xhr = new XMLHttpRequest();
// 设置响应体数据的类型
xhr.responseType = 'json';
// 初始化
xhr.open('GET', 'http://localhost:8080/json-server');
// 发送
xhr.send();
// 事件绑定
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
// console.log(xhr.response);
// result.innertHTML = xhr.response;
// 手动对数据进行转换,字符串转换为对象
// let data = JSON.parse(xhr.response);
// console.log(data);
// result.innerHTML = data.name;
// 自动转换---上面设置响应体数据的类型
console.log(xhr.response);
result.innerHTML = xhr.response.name;
}
}
}
}
</script>
</body>
</html>
2-5 IE缓存问题解决
<!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 #258;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn = document.getElementsByTagName('button')[0];
const result = document.querySelector('#result');
btn.addEventListener('click', function() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8080/ie");
// ajax解决IE请求缓存问题
xhr.open("GET", "http://localhost:8080/ie?t=+Date.now()");
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
}
})
</script>
</body>
</html>
2-6 请求超时与网络异常处理
<!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>请求超时与网络异常</title>
<style>
#result {
width: 200px;
height: 100px;
border: 1px solid #258;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn = document.getElementsByTagName('button')[0];
const result = document.querySelector('#result');
btn.addEventListener('click', function() {
const xhr = new XMLHttpRequest();
// 超时设置 2s
xhr.timeout = 2000;
// 超时回调
xhr.ontimeout = function() {
alert("网络异常,请稍后再试!");
}
// 网络异常的回调
xhr.onerror = function() {
alert("你的网络似乎出了一些问题");
}
xhr.open("GET", 'http://localhost:8080/delay');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
}
})
</script>
</body>
</html>
2-7 jQuery发送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">
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.1/css/bootstrap-grid.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<title>Document</title>
</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>
</div>
<script>
$('button').eq(0).click(function() {
$.get("http://localhost:8080/jQuery-server", {
a: 100,
b: 200
}, function(data) {
console.log(data);
})
})
$('button').eq(1).click(function() {
$.get("http://localhost:8080/jQuery-server", {
a: 100,
b: 200
}, function(data) {
console.log(data);
}, 'json')
})
$('button').eq(2).click(function() {
$.ajax({
// url
url: 'http://localhost:8080/delay',
// 参数
data: {
a: 100,
b: 200
},
// 请求类型
type: 'GET',
// 响应体结果
dataType: 'json',
success: function(data) {
console.log(data);
},
// 超时时间
timeout: 2000,
// 失败的回调
error: function() {
console.log('出错了!');
},
// // 头信息
// headers: {
// c: 300,
// d: 400
// }
})
})
</script>
</body>
</html>