1.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>
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px #90b;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn = document.getElementsByTagName('button')[0];
const result = document.getElementById('result');
btn.onclick = function(){
// 1.创建对象
const xhr = new XMLHttpRequest();
// 2.初始化设置请求方法和url
xhr.open('GET','http://127.0.0.1:8000/server?a=200&b=300&c=300');
// 3.发送
xhr.send();
// 4.事件绑定,处理服务端返回的结果
// on 当...时
// readystate 是 xhr对象中的属性,表示状态的值:
// 0未初始化,1表示open方法调用完毕,2.表示send方法调用完毕,3.表示服务端返回了部分结果,4表示服务端返回了所有结果
// change当改变时候触发 onreadystatechange触发了四次
xhr.onreadystatechange = function(){
// 判断(服务端返回了所有结果)
if(xhr.readyState === 4){
// 判断响应状态码
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的文本
result.innerHTML = xhr.response;
}else{
}
}
}
}
</script>
</body>
</html>
可以用express写一个简单的本地服务器
// 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 JSON--2');
})
app.all('server',(request,response)=>{
// 设置响应头,允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
// 设置响应头
response.setHeader('Access-Control-Allow-Headers','*');
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:'yangy'
}
// 对对象进行字符串的转换
let str = JSON.stringify(data);
// 设置响应体
response.send(data);
})
// 针对IE缓存
app.get('/ie',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
// 设置响应体
response.send('HELLO IE--3');
})
//延时响应
app.get('/delay',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
setTimeout(()=>{
// 设置响应体
response.send('延时响应');
},3000)
})
// jQuery 服务
app.all('/jquery',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
const data = {
name:'yangy'
}
response.send(JSON.stringify(data));
})
// axios服务
app.all('/axios',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
const data = {
name:'yangy'
}
response.send(JSON.stringify(data));
})
// fetch服务
app.all('/fetch',(request,response)=>{
response.setHeader('Access-Control-Allow-Origin','*');
response.setHeader('Access-Control-Allow-Headers','*');
const data = {
name:'yangy'
}
response.send(JSON.stringify(data));
})
// 4.监听端口启动
app.listen(8000,()=>{
console.log("服务已经启动,8000端口监听中...");
})
app.all是处理所有的请求
2.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>AJAX post请求</title>
<style>
#result{
width: 200px;
height: 100px;
border:solid 1px #903;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
// 获取元素对象
const result = document.getElementById('result');
// 绑定事件
result.addEventListener('mouseover',()=>{
// 1.创建对象
const xhr = new XMLHttpRequest();
// 2.初始化 设置类型与url
xhr.open('POST','http://127.0.0.1:8000/server');
// 设置请求头
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('name','yangy');
// 3.发送
xhr.send('a=100&b=200&c=300');
// 4.事件绑定
xhr.onreadystatechange = function(){
// 判断
if(xhr.readyState === 4){
if(xhr.status>=200 && xhr.status<300){
console.log(xhr);
console.log(xhr.response);
// 处理服务端返回的结果
result.innerHTML = xhr.response
}
}
}
})
</script>
</body>
</html>
3.响应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>Document</title>
<style>
#result{
width: 200px;
height: 200px;
border:solid 1px #89b;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
const result = document.getElementById('result');
// 绑定键盘按下事件
window.onkeydown = function(){
// console.log('test');
// 1.创建对象
const xhr = new XMLHttpRequest();
// 设置响应体数据的类型
xhr.responseType = 'json';
// 2..初始化请求类型,和url
xhr.open('GET','http://127.0.0.1:8000/json-server');
// 3.发送
xhr.send();
// 4.事件绑定
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status>=200 && xhr.status<300){
// console.log(xhr.response);
// 1.手动数据转换
// let data = JSON.parse(xhr.response);
// console.log(data);
// result.innerHTML = data.name;
console.log(xhr.response);
// 2.自动数据转换
result.innerHTML = xhr.response.name;
}
}
}
}
</script>
</body>
</html>
4.针对IE浏览器缓存问题
在请求地址之后加入时间戳,可以避免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: 200px;
border: solid 1px #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(){
// 1.创建对象
const xhr = new XMLHttpRequest();
// 2.设置请求类型,请求url
xhr.open('GET','http://127.0.0.1:8000/ie?t=' +Date.now());
// 3.发送
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status>=200 && xhr.status<300){
result.innerHTML = xhr.response;
}
}
}
})
</script>
</body>
</html>
5.请求超时和网络异常
<!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:solid 1px #90b;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn = document.getElementsByTagName('button')[0];
const result = document.querySelector('#result');
btn.addEventListener('click',()=>{
// 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/delay');
// 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>
6.取消请求
用abort取消请求
<!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>
</head>
<body>
<button>点击发送</button>
<button>点击取消</button>
<script>
// 获取元素对象
const btns = document.querySelectorAll('button');
let xhr1 = null;
btns[0].onclick = function(){
xhr1 = new XMLHttpRequest();
xhr1.open('GET','http://127.0.0.1:8000/delay');
xhr1.send();
}
btns[1].onclick = function(){
xhr1.abort();
}
</script>
</body>
</body>
</html>
7.重复请求的问题
需要在全局设置变量
<!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>
</head>
<body>
<button>点击发送</button>
<script>
// 获取元素对象
const btns = document.querySelectorAll('button');
let xhr1 = null;
// 标识变量
let isSending = false; //是否正在发送AJAX请求
btns[0].onclick = function(){
// 判断标识变量
if(isSending){
xhr1.abort();
}
// 如果正在发送,则取消该请求,创建一个新的请求
xhr1 = new XMLHttpRequest();
isSending = true;
xhr1.open('GET','http://127.0.0.1:8000/delay');
xhr1.send();
xhr1.onreadystatechange = function(){
if(xhr1.readyState === 4){
// 修改标识变量
isSending = false;
}
}
}
</script>
</body>
</body>
</html>