一:Ajax简介
Ajax全称Asynchronous JavaScript And XML,指异步的js和xml,Ajax不是新的编程语言,而是将现有标准组合在一起使用的新方式
二:Ajax特点
1:优点
- 无需刷新页面与服务器端通信
- 允许根据用户事件更新页面部分内容
2:缺点
- 没有浏览历史,无法回退
- 存在跨域问题
- SEO不友好
三:HTTP协议
1:概念
HTTP协议 超文本传输协议,协议详细规定了浏览器和万维网服务器之间相互通信的规则
2:请求报文
a:请求行
- 请求方法:常见的是GET和POST,此外还有DELETED等
- 请求地址:和报文头组成完整的url请求
- 协议名称及版本号:一般是HTTP/1.1
b:请求头
- HTTP报文头,包含若干个属性,格式为"属性名: 属性值"
c:请求体
如果请求方法为GET,则请求体为空
3:响应报文
a:响应行
- 响应协议
- 状态码
- 描述
b:响应头
响应名: 响应值
c:响应体
响应参数
四:AJAX请求基本操作
1:使用express开启后端
引入nodemon
npm install -g nodemon
引入express
npm i express
2:开启服务器
// 引入express
const express = require('express');
// 创建应用对象
const app = express();
// 创建路由规则
// request是请求报文的封装
// response是响应报文的封装
app.get('/server',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
// 设置响应
response.send("hello ajax");
});
// 监听端口启动
app.listen(8000,()=>{
console.log("已启动");
})
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>Ajax请求</title>
<style>
#cls{
width: 300px;
height: 200px;
border: solid;
}
</style>
</head>
<body>
<button>点击</button>
<div id="cls"></div>
<script>
const btn = document.getElementsByTagName("button")[0];
const result = document.getElementById("cls");
// 绑定事件
btn.onclick = function(){
//创建对象
const xhr = new XMLHttpRequest();
// 初始化。设置请求方法和url,并传请求参数
xhr.open('GET',"http://localhost:8000/server?a=100&b=114")
// 发送
xhr.send();
//取消发送
x.abort();
// 设置超时,2秒后为返回结果取消请求
xhr.timeout = 2000;
// 超时提醒
xhr.ontimeout = function(){
alert("网络异常,稍后重试")
}
// 事件绑定,处理服务器返回结果
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.getAllResponseHeaders);//响应头
console.log(xhr.response);//响应体
result.innerHTML=xhr.response;
}
}
}
}
</script>
</body>
</html>
查看AJAX请求
4:AJAX实现post请求
// 引入express
const express = require('express');
// 创建应用对象
const app = express();
// 创建路由规则
// request是请求报文的封装
// response是响应报文的封装
app.get('/server',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
// 设置响应
response.send("hello ajax");
});
app.post('/server',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
// 设置响应
response.send("hello ajax POST-Request");
});
// 监听端口启动
app.listen(8000,()=>{
console.log("已启动");
})
<!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请求</title>
<style>
#result{
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
const result = document.getElementById("result");
// 绑定事件
result.addEventListener("mouseover",function(){
console.log("test")
// 创建对象
const xhr = new XMLHttpRequest();
// 初始化请求类型
xhr.open('POST',"http://localhost:8000/server");
// 设置请求头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
xhr.send('user:admin&password:123456');
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
// 处理服务端
result.innerHTML = xhr.response;
}
}
}
});
</script>
</body>
</html>
查看载荷
5:AJAX响应JSON数据
// 引入express
const express = require('express');
// 创建应用对象
const app = express();
// 创建路由规则
// request是请求报文的封装
// response是响应报文的封装
app.get('/server',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
// 设置响应
response.send("hello ajax");
});
app.post('/server',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
// 设置响应
response.send("hello ajax POST-Request");
});
app.all('/serverall',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
const data = {
name:'lunai'
}
//
let str = JSON.stringify(data)
// 设置响应
response.send(str);
});
// 监听端口启动
app.listen(8000,()=>{
console.log("已启动");
})
<!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请求</title>
<style>
#result{
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
const result = document.getElementById("result");
// 标识变量
let isSeading = false;
// 绑定事件
result.addEventListener("mouseover",function(){
// 判断是否已经发送请求服务器操作
if(isSeading)
xhr.abort();
console.log("test")
// 创建对象
const xhr = new XMLHttpRequest();
// 设置响应数据类型
xhr.responseType = 'json';
isSeading = true;
// 初始化请求类型
xhr.open('POST',"http://localhost:8000/serverall");
// 设置请求头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
xhr.send('user:admin&password:123456');
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
// 处理服务端
result.innerHTML = xhr.response.name;
}
}
}
});
</script>
</body>
</html>
6:JQuery发送AJAX请求
要先引入JQuery
<script src="https://code.jquery.com/jquery-3.1.1.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>Ajax请求</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<style>
#result{
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<div id="result">
<h2>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:8000/jquery",{a:114,b:514},function(data){
console.log(data)
})
})
$('button').eq(1).click(function(){
$.post("http://localhost:8000/jquery",{a:114,b:514},function(data){
console.log(data)
},'json');
})
$('button').eq(2).click(function(){
$.ajax({
url: 'http://localhost:8000/jquery',
data: {a:100,b:200},
// 请求类型
type: 'POST',
dataType: 'json',
success: function(data){
console.log(data)
}
})
})
</script>
</body>
</html>
// 引入express
const express = require('express');
// 创建应用对象
const app = express();
// 创建路由规则
// request是请求报文的封装
// response是响应报文的封装
app.get('/server',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
// 设置响应
response.send("hello ajax");
});
app.post('/server',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
// 设置响应
response.send("hello ajax POST-Request");
});
app.post('/jquery',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
// 设置响应
const data={name: 'lunai'}
response.send(JSON.stringify(data));
});
app.get('/jquery',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
// 设置响应
response.send("hello jquery");
});
app.all('/serverall',(request,response)=>{
// 设置响应头 允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
const data = {
name:'lunai'
}
//
let str = JSON.stringify(data)
// 设置响应
response.send(str);
});
// 监听端口启动
app.listen(8000,()=>{
console.log("已启动");
})