ajax的基础操作
1.HTTP
HTTP(hypertext transport protocol)协议『超文本传输协议』,协议详细规定了浏览器和万维网服务器之间互相通信的规则。
约定, 规则
1.请求报文
重点是格式与参数
行 POST /s?ie=utf-8 HTTP/1.1
头 Host: atguigu.com
Cookie: name=guigu
Content-type: application/x-www-form-urlencoded
User-Agent: chrome 83
空行
体 username=admin&password=admin
2.响应报文
行 HTTP/1.1 200 OK
头 Content-Type: text/html;charset=utf-8
Content-length: 2048
Content-encoding: gzip
空行
体 <html>
<head>
</head>
<body>
<h1>尚硅谷</h1>
</body>
</html>
- 404
- 403
- 401
- 500
- 200
2.ajax的基本操作:
1.AJAX发送get请求
<!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>
</body>
<script>
//获取button元素
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=100&b=200&c=300');
//3.发送
xhr.send();
//4.事件绑定,处理服务端返回的结果
// on when 表示当...时候
//readychange 是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的文本
result.innerHTML=xhr.response;
} else{
}
}
}
}
</script>
</html>
node的服务器代码:
//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');
});
//4.监听端口启动服务
app.listen(8000,()=>{
console.log("服务已经启动,8000端口监听中......");
})
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: 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://127.0.0.1:8000/server');
//3.发送 //post设置参数 可以设置任意的格式
// xhr.send('a=100&b=200&c=300');
xhr.send('a:100&b:200&c:300');
//4.事件绑定
xhr.onreadystatechange=function(){
//判断(服务器返回来所有的结果)
if(xhr.readyState===4){
//判断响应状态码 200 404 403 401 500
//其实状态码为2xx 都是成功
if(xhr.status>=200&&xhr.status<300){
//设置result的文本
result.innerHTML=xhr.response;
} else{
}
}
}
});
</script>
</body>
</html>
服务器补充:
app.post('/server',(request,response)=>{
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//设置响应
response.send('HELLO AJAX POST!!!');
});
3.all可以接受任意的请求:
代码
//可以接受任意的请求
app.all('/server',(request,response)=>{
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//响应头
response.setHeader('Access-Control-Allow-Headers','*');
//设置响应
response.send('HELLO AJAX POST!!!');
});
4.自定义请求头:
xhr.setRequestHeader('name','jinggangshan');
需要在服务器端设置响应头:
//响应头
response.setHeader('Access-Control-Allow-Headers','*');
5.ajax的JSON数据格式请求操作
//获取对象
const result=document.getElementById('result');
//绑定键盘按下事件
window.onkeydown=function(){
//创建对象
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){
// result.innerHTML=xhr.response;
//手动对数据进行转换
// let data=JSON.parse(xhr.response);
// console.log(data);
// result.innerHTML=data.name;
//自动转换
console.log(xhr.response);
result.innerHTML=xhr.response.name;
}else{
}
}
}
}
5.1服务器请求:
app.all('/json-server',(request,response)=>{
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//响应头
response.setHeader('Access-Control-Allow-Headers','*');
//响应一个数据
const data={
name:'jinggangshan'
};
//对对象进行一个字符串的转换
let str=JSON.stringify(data);
//设置响应
response.send(str);
5.2 node服务器工具包:
nodemon:安装命令:npm install -g nodemon
6.处理IE缓存问题:
const btn=document.getElementsByTagName('button')[0];
const result=document.getElementById('result');
btn.addEventListener("click",function(){
const xhr=new XMLHttpRequest();
//此处加上时间戳来表示每次请求都是不一样的来处理ie缓存问题
xhr.open("GET","http://127.0.0.1:8000/ie?t="+Date.now());
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status>=200&&xhr.status<300){
result.innerHTML=xhr.response;
}
}
}
})
7.请求超时和网络异常
代码:
btn.addEventListener("click",function(){
const xhr=new XMLHttpRequest();
//超时设置 2s
xhr.timeout=2000;
//超时回调
xhr.ontimeout=function(){
alert("网络异常,请稍后重试")
}
//网络异常回调
xhr.onerror=function(){
alert("你的网络似乎出了一些问题")
}
xhr.open("GET","http://127.0.0.1:8000/delay");
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status>=200&&xhr.status<300){
result.innerHTML=xhr.response;
}
}
}
})
node服务器代码:
//延时响应
app.get('/delay',(request,response)=>{
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
setTimeout(()=>{
//设置响应
response.send('延时响应');
},3000)
});
8.Ajax的手动取消操作
const btns=document.getElementsByTagName('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();
}
9.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>重复请求问题</title>
</head>
<body>
<button>点击发送</button>
<script>
//获取元素对象
const btns=document.getElementsByTagName('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://127.0.0.1:8000/delay");
x.send();
x.onreadystatechange=function(){
if(x.readyState===4){
//修改变量标识
isSending=false;
}
}
}
</script>
</body>
</html>
10.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">
<title>jquery里面的ajax</title>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.2/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.2/js/bootstrap.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.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>
</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);
});
})
$('button').eq(2).click(function(){
$.ajax({
//url
url:'http://127.0.0.1:8000/jquery-server',
//参数
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>
服务器代码:
//jquery服务
app.all('/jquery-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 JQUERY AJAX');
});
11.利用axios发送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>9-axios发送ajax请求</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.3/axios.min.js"></script>
</head>
<body>
<button>GET</button>
<button>POST</button>
<button>AJAX</button>
<script>
const btns=document.querySelectorAll('button');
//配置baseURL
axios.defaults.baseURL='http://127.0.0.1:8000';
btns[0].onclick=function(){
//GET请求
axios.get('/axios-server',{
//url参数
params:{
id:100,
vip:7
},
headers:{
name:'jinggangshan',
age:20
}
}).then(value=>{
console.log(value);
})
}
btns[1].onclick=function(){
//post请求
axios.post('/axios-server',{
username:'admin',
password:'admin'
},
{
params:{
id:200,
vip:9
},
//请求头
headers:{
height:180,
weight:180
},
})
}
btns[2].onclick=function(){
axios({
//请求方法:
method:'POST',
//url
url:'/axios-server',
//url参数
params:{
vip:10,
level:30
},
//头信息
headers:{
a:100,
b:200
},
//请求体参数
data:{
username:'admin',
password:"admin"
}
}).then(response=>{
console.log(response);
//响应状态码
console.log(response.status);
//响应状态字符串
console.log(response.statusText);
//响应头信息
console.log(response.headers);
//响应体信息
console.log(response.data);
})
}
</script>
</body>
</html>
12.利用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>10-利用fetch函数来发送ajax请求</title>
</head>
<body>
<button>ajax</button>
<script>
const btn=document.querySelector('button');
btn.onclick=function(){
//请求的方法
fetch('http://127.0.0.1:8000/fetch-server?vip=10',{
//请求方法
method:'POST',
//请求头
headers:{
name:'jinggangshan',
},
//请求体
body:'username=admin&password=admin'
}).then(response=>{
return response.text();
//return response.json();
}).then(response=>{
console.log(response)
});
}
</script>
</body>
</html>
3.同源策略
含义:
同源策略(Same-Origin Policy)最早由 Netscape 公司提出,是浏览器的一种安全策略。
同源: 协议、域名、端口号 必须完全相同。
违背同源策略就是跨域
代码示例:
<!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>
<h1>我家</h1>
<button>点击获取用户数据</button>
<script>
const x=new XMLHttpRequest();
//这是因为满足同源策略的,所以url简写地址
x.open("GET",'/data');
//发送
x.send();
x.onreadystatechange=function(){
if(x.readyState===4){
if(x.status>=200&&x.status<300){
console.log(x.response);
}
}
}
</script>
</body>
</html>
4.jsonp的实现原理
1) JSONP 是什么
JSONP(JSON with Padding),是一个非官方的跨域解决方案,纯粹凭借程序员的聪明
才智开发出来,只支持 get 请求。
2) JSONP 怎么工作的?
在网页有一些标签天生具有跨域能力,比如:img link iframe script。
JSONP 就是利用 script 标签的跨域能力来发送请求的
3.案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>案例</title>
</head>
<body>
用户名: <input type="text" id="username">
<p></p>
<script>
//获取 input 元素
const input = document.querySelector('input');
const p = document.querySelector('p');
//声明 handle 函数
function handle(data){
input.style.border = "solid 1px #f00";
//修改 p 标签的提示文本
p.innerHTML = data.msg;
}
//绑定事件
input.onblur = function(){
//获取用户的输入值
let username = this.value;
//向服务器端发送请求 检测用户名是否存在
//1. 创建 script 标签
const script = document.createElement('script');
//2. 设置标签的 src 属性
script.src = 'http://127.0.0.1:8000/check-username';
//3. 将 script 插入到文档中
document.body.appendChild(script);
}
</script>
</body>
</html>
服务器代码:
//用户名检测是否存在
app.all('/check-username',(request, response) => {
// response.send('console.log("hello jsonp")');
const data = {
exist: 1,
msg: '用户名已经存在'
};
//将数据转化为字符串
let str = JSON.stringify(data);
//返回结果
response.end(`handle(${str})`);
});
5.JQuery 解决跨域请求
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery-jsonp</title>
<style>
#result{
width:300px;
height:100px;
border:solid 1px #089;
}
</style>
<script crossorigin="anonymous" src='https://cdn.bootcss.com/jquery/3.5.0/jquery.min.js'></script>
</head>
<body>
<button>点击发送 jsonp 请求</button>
<div id="result">
</div>
<script>
$('button').eq(0).click(function(){
$.getJSON('http://127.0.0.1:8000/jquery-jsonp-server?callback=?', function(data){
$('#result').html(`
名称: ${data.name}<br>
校区: ${data.city}
`)
});
});
</script>
</body>
</html>
服务器代码:
app.all('/jquery-jsonp-server',(request, response) => {
// response.send('console.log("hello jsonp")');
const data = {
name:'尚硅谷',
city: ['北京','上海','深圳']
};
//将数据转化为字符串
let str = JSON.stringify(data);
//接收 callback 参数
let cb = request.query.callback;
//返回结果
response.end(`${cb}(${str})`);
});
6.cors解决跨域请求
1) CORS 是什么?
CORS(
Cross-Origin Resource Sharing),跨域资源共享。CORS 是官方的跨域解决方
案,它的特点是不需要在客户端做任何特殊的操作,完全在服务器中进行处理,支持
get 和 post 请求。跨域资源共享标准新增了一组 HTTP 首部字段,允许服务器声明哪些
源站通过浏览器有权限访问哪些资源
2) CORS 怎么工作的?
CORS 是通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应
以后就会对响应放行。
3.cros的使用:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CORS</title>
<style>
\#result{
width:200px;
height:100px;
border:solid 1px #90b;
}
</style>
</head>
<body>
<button>发送请求</button>
<div id="result"></div>
<script>
const btn = document.querySelector('button');
btn.onclick = function(){
//1. 创建对象
const x = new XMLHttpRequest();
//2. 初始化设置
x.open("GET", "http://127.0.0.1:8000/cors-server");
//3. 发送
x.send();
//4. 绑定事件
x.onreadystatechange = function(){
if(x.readyState === 4){
if(x.status >= 200 && x.status < 300){
//输出响应体
console.log(x.response);
}
}
}
}
</script>
</body>
</html>
服务器代码:
app.all('/cors-server', (request, response)=>{
//设置响应头
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", '*');
response.setHeader("Access-Control-Allow-Method", '*');
// response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");
response.send('hello CORS');
});
学习来源:
https://www.bilibili.com/video/BV1WC4y1b78y/?spm_id_from=333.337.search-card.all.click
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)