原生AJAX
AJAX简介
- AJAX全称为Asynchronous JavaScript And XML,就是异步的JS和XML
- 通过AJAX可以在浏览器中向服务器发送异步请求,最大的优势:无刷新获取数据
- AJAX不是新的编程语言,而是一种将现有的标准组合在一起使用的新方式
XML简介
- XML:可扩展标记语言
- XML被设计用来传输和存储数据
- XML和HTML类似,不同的是HTML中都是预定义标签,而XML中没有预定义标签,全都是自定义标签,用来表示一些数据
name="孙悟空";
age=18;
gender="男";
<student>
<name>孙悟空</name>
<age>18</age>
<gender>男</gender>
</student>
{"name":"孙悟空"."age":18,"gender":"男"}
AJAX的特点
AJAX的优点
- 可以无需刷新页面而与服务器端进行通信
- 允许你根据用户事件来更新部分页面内容
AJAX的缺点
- 没有浏览历史,不能回退
- 存在跨域问题(同源)
- SEO(搜索引擎优化)不友好
HTTP协议
- HTTP(hypertext transport protocol)协议【超文本传输协议】
- 协议相许规定了浏览器和万维网服务器之间互相通信的规则
请求(请求报文)
行 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
响应(响应报文)
行 HTTP/1.1 200 OK
头 Content-type: text/html;charset=utf-8
Content-length: 2048
Content-encoding: gzip
空行
体 html内容
Express的使用
【终端】npm init --yes
【终端】npm i express
【JS】
const expree = require('express');
const app = express();
app.get('/server', (request,response)=> {
response.setHeader('Access-Control-Allow-Origin','*')
response.send("HELLO EXPRESS")
})
app.post('/server', (request,response)=> {
response.setHeader('Access-Control-Allow-Origin','*')
response.send("HELLO EXPRESS")
})
app.listen(8000, ()=> {
console.log("服务已经启动,8000端口监听中...")
})
【终端】node js文件路径
【浏览器】访问本地ip或者localhost+端口
AJAX的基本操作
let xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.timeout = 2000;
xhr.ontimeout = function() {
alert('网络超时');
}
xhr.onerror = funtion() {
alert('网络异常');
}
xhr.open('GET','http://localhost:8000/server?t=' + Date.now());
xhr.open('POST','http://localhost:8000/server?a=100&b=200&c=300');
xhr.serRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
xhr.send(a=100&b=200&c=300);
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)
let data = JSON.parse(xhr.response);
}
}
}
xhr.abort();
JQuery请求AJAX
GET
$.get(
'localhost:8000/server',
{a:100, b:200},
function(data) {
},'json')
POST
$.post(
'localhost:8000/server',
{a:100, b:200},
function(data) {
})
JQuery通用方法发送AJAX请求
$.ajax({
url: 'localhost:8000/server',
data: {a:100, b:200},
type: 'GET',
dataType: 'json',
success: function(data) {},
timeout: 2000,
error: function(err) {},
headers: {c:300, d:400}
})
AXIOS请求AJAX
GET
axios.defaults.baseURL = 'localhost:8000'
axios.get(
'/server',
{
params: {id:100, vip:7},
headers: {age:20},
}
}).then(data => {})
POST
axios.defaults.baseURL = 'localhost:8000'
axios.post(
'/server',
{username: 'admin', password: 'admin'},
{
params: {id:100, vip:7},
headers: {age:20},
}
}).then(data => {})
AXIOS通用方法发送AJAX请求
axios({
method: 'POST',
url: '/server',
params: {
vip: 10,
level: 30
},
headers: {
a:100,
b:200
},
data: {
username: 'admin',
password: 'admin'
}
}).then(data => {
console.log(data.status);
console.log(data.statusText);
console.log(data.headers);
console.log(data.data)
})
使用fetch函数发送AJAX请求
fetch(
'localhost:8000/server?vip=10',
{
method: 'POST',
headers: {
name: 'atguigu'
},
body: 'username=admin&password=admin'
}
).then(data => {
return response.text();
return response.json();
}).then(data => {
console.log(data)
})
跨域
同源策略
- 同源策略(Same-Origin-Policy)最早由Netscape公司提出,是浏览器的一种安全策略。
- 同源:协议、域名、端口号,必须完全相同
- 违背同源策略就是跨域
如何解决跨域
JSONP
- JSONP是什么
- JSONP(JSON with Padding),是一个非官方的跨域解决方案,纯粹凭借程序员的聪明才智开发出来的,只支持get请求。
- JSONP怎么工作的?
- 在网页有一些标签天生具有跨域能力,比如:img link iframe script
- JSONP就是利用script标签的跨域能力开发送请求的
- JSONP的使用
- 动态的创建一个script标签:
var script = document.createElement("script")
- 设置script的src,设置回调函数:
script.src="http://localhost:3000/testAJAX?callback=abc"
- 将script插入到文档中:
document,body.appendChild(script)
CORS
CORS是什么?
- CORS(Cross-Origin Resource Sharing),跨域资源共享。CORS是官方的跨域解决方案,它的特点是不需要在客户端做任何特殊的操作,完全在服务器中进行处理,支持get和post的请求。跨域资源共享标准新增了一组http首部字段,允许服务器声明哪些源站通过浏览器有权限访问哪些资源
CORS怎么工作的?
- CORS是通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应以后就会对响应放行。
- CORS的使用
response.setHeader("Access-Control-Allow-Origin","*")