Ajax
Ajax
1、http协议
什么是http协议
传输协议。
前端以什么样的形式给服务器传送数据
服务器以什么样的形式给前端传送数据
常见的协议类型
TCP
保证数据的顺序,尽量不丢失数据。
传输效率不高,只支持1对1.
UDP
不保证数据的顺序,不保证是否丢失数据。
传输效率高,支持1对多,多对1
张老师是个超级有趣的年轻小伙子 = 年轻小伙子超级有趣的
http传输过程
1.四个步骤:
1-1:建立连接
1-2:发送请求(客户端发送给服务器)
1-3:返回响应(服务器发送给客户端)
1-4:断开连接。
2 只能由客户端发起,不能由服务器发起。
3 交互数据只能是字符串。
TCP三次握手 四次挥手
目的:保证传输通道的连接。
- 三次握手:
- 四次挥手:
请求报文
请求报文由三部分组成:
1.请求行
get/post 请求方式
api/v1/topic_collect/alsotang 请求地址
http/1.1 传输协议以及版本
2.请求头
host:请求主机
Accapt:期望接受的数据类型
UserAgent:请求终端的信息
cookie
referer:表示请求是从哪个url进来的。
3.请求体
前端给后端(客户端给服务端)的数据。
get请求:参数会以键值对的形式,用&连接,拼接在URL的后面。键与值之间用=连接。
post:参数不是放在url后面,而是放在requestbody中。
响应报文
响应报文由三部分组成:
1.状态行
http/1.1 传输协议以及版本
200 状态响应码
ok 对响应码简单的描述。
2.响应头
Date:服务器事件
Server:服务器信息
Content-type:响应体的数据格式以及编码。
3.响应体
后端给前端的数据
2、Ajax介绍
Asynchronous javascript and xml 异步js和xml
xml:存储数据的格式。 现在用json。
异步和同步
js是单线程的语言。
同步:上面的代码未完成时,下面的代码不会去执行。
异步:上面的代码未完成时,下面的代码也可以执行。
setTimeout(()=>{
console.log("延时函数");
},0);
console.log("延时函数后的代码");
在延时函数中,虽然延迟时间为0,但是仍然是一个异步代码。异步代码总会在同步之后执行。
传统的前后端交互的缺点
传统的前后端交互是前后端不分离的,用户触发一个http请求,服务器接受以后,会做出响应,响应的是一个新的页面。也就是说,数据的刷新是通过页面的刷新或者页面的跳转来实现的。
比如:视频页面下方的留言功能。
缺点:
1.用户体验非常不好。
2.因为少量数据的更新而去刷新这个页面,造成了资源的浪费,同时也会对服务器造成巨大的压力。
为了解决这个问题,我们急需一种,不用刷新整个页面,只更新部分数据的技术。ajax就是这样的一门技术。 2005年的时候诞生。
3、Ajax的特点
优点:
不需要别的插件,或者引入别的文件,浏览器默认就支持Ajax。
用户体验特别好。
提高性能。(在传输数据的时候不需要整体提交,只需要提交少量的数据。)、
减轻服务器的压力
缺点:
前进,后退功能无效。
搜索引擎的支持度不够。
4、状态码与状态值
响应状态码:本次请求的响应状态
值的范围:100-599
100-199 表示连接继续。
200-299 表示各种意义上的成功
300-399 表示重定向。
400-499 表示客户端错误
500-599 表示服务器错误
常见的状态值
101 表示连接继续
200 成功
302 临时重定向
301 永久重定向
304 缓存
当你访问这个页面之后,浏览器会自动缓存, 再次访问时,浏览器不会向服务器发送请求了,而是从缓存中获取。
403 无访问权限
404 访问地址不存在
500 服务器错误
请求方式
get/post
get:
语义:获取
get参数是在地址栏中
参数4KB大小。
get请求会被浏览器缓存
post:
语义:发送
post参数是requestBoby
大小不受客户端限制,但是可能会被服务器限制。
post请求不会被浏览器缓存,除非通过程序去修改
请求相对于get比较安全。
5、Ajax使用
1.创建一个xmlhttprequest对象。
2.调用对象的open方法
3.调用对象的send方法
4.onreadystatechange函数,响应时会自动调用。
(1)发送一个get请求
<style>
#box {
margin-top: 20px;
background-color: skyblue;
}
</style>
<script>
function sendMsg() {
//1.创建一个xmlhttpRequset对象
var xhr = new XMLHttpRequest();
// 2.调用open方法
//open方法有三个参数:
// 1.请求的方式 method get/post
// 2.请求的url
// 3.是否异步,默认值true,可选参数.
// https://cnodejs.org/api/v1/topics
xhr.open("get", "http://localhost/data.php?id=1");
//3.调用send方法
xhr.send();
//4.监听状态的改变。
xhr.onreadystatechange = function () {
//状态值 :0-4 4表示完成
if (xhr.readyState === 4) {
//判断状态码
if (xhr.status === 200) {
//responseText 返回的数据
var box = document.getElementById("box")
var res = JSON.parse(xhr.responseText);
box.innerHTML = `
<h2>编号为:${res.id}</<h2>
<h2>标题为:${res.title}</<h2>
`;
}
}
}
}
window.onload = function(){
var btn = document.getElementById("btn");
btn.onclick = sendMsg;
}
</script>
</head>
<body>
<button id="btn">发送请求</button>
<div id="box">
</div>
</body>
(2)发送一个post请求
<style>
#box {
margin-top: 20px;
background-color: skyblue;
}
</style>
<script>
function sendMsg() {
//1.创建一个xmlhttpRequset对象
var xhr = new XMLHttpRequest();
// 2.调用open方法
//open方法有三个参数:
// 1.请求的方式 method get/post
// 2.请求的url
// 3.是否异步,默认值true,可选参数.
xhr.open("post", "http://localhost/post.php");
//3.调用send方法
//post请求需要设置请求头。
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
xhr.send("id=2");
//4.监听状态的改变。
xhr.onreadystatechange = function () {
//状态值 :0-4 4表示完成
if (xhr.readyState === 4) {
//判断状态码
if (xhr.status === 200) {
console.log(xhr.responseText);
//responseText 返回的数据
var box = document.getElementById("box")
var res = JSON.parse(xhr.responseText);
box.innerHTML = `
<h2>编号为:${res.id}</<h2>
<h2>标题为:${res.title}</<h2>
`;
}
}
}
}
window.onload = function(){
var btn = document.getElementById("btn");
btn.onclick = sendMsg;
}
</script>
</head>
<body>
<button id="btn">发送请求</button>
<div id="box">
</div>
</body>
(3)封装get请求
<style>
#box {
margin-top: 20px;
background-color: skyblue;
}
</style>
<!-- <script src="js/utils.js"></script> -->
<script>
function get(url, query, callback, isJson = true) {
var xhr = new XMLHttpRequest();
// 如果有参数,需要把参数拼接到url后面。
if (query) {
url += "?";
for (const key in query) {
url += `${key}=${query[key]}&`
}
// url = url+"id=1&name=zhangsan&"
// 负数是倒数开始截取。
url = url.slice(0, -1);
}
xhr.open("get", url);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var res = isJson ? JSON.parse(xhr.responseText) : xhr.responseText;
callback(res);
}
}
}
}
window.onload = function() {
var btn = document.getElementById("btn");
btn.onclick = function() {
get("http://localhost/data.php", {
id: 1
}, function(res) {
var box = document.getElementById("box")
box.innerHTML = `
<h2>编号为:${res.id}</<h2>
<h2>标题为:${res.title}</<h2>
`;
})
};
}
</script>
</head>
<body>
<button id="btn">发送请求</button>
<div id="box">
</div>
</body>
(4)封装post请求
<style>
#box {
margin-top: 20px;
background-color: skyblue;
}
</style>
<script>
function post(url, query, callback, isJson = true) {
var str = "";
if (query) {
for (const key in query) {
str += `${key}=${query[key]}&`
}
str = str.slice(0, -1);
}
var xhr = new XMLHttpRequest();
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.send(str);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var res = isJson ? JSON.parse(xhr.responseText) : xhr.responseText;
callback(res);
}
}
}
}
window.onload = function() {
var btn = document.getElementById("btn");
btn.onclick = function() {
post("http://localhost/post.php", {
id: 2
}, function(res) {
var box = document.getElementById("box")
box.innerHTML = `
<h2>编号为:${res.id}</<h2>
<h2>标题为:${res.title}</<h2>
`;
})
};
}
</script>
</head>
<body>
<button id="btn">发送请求</button>
<div id="box">
</div>
</body>
(5)封装ajax请求
<style>
#box {
margin-top: 20px;
background-color: skyblue;
}
</style>
<script>
//形参: {method, url, query, callback, isJson = true}
function ajax(params) {
var xhr = new XMLHttpRequest();
if (params.method.toLowerCase() === "get") {
var url = params.url;
if (params.query) {
url += "?";
for (const key in params.query) {
url += `${key}=${params.query[key]}&`
}
url = url.slice(0, -1);
}
xhr.open("get", url);
xhr.send();
} else {
var str = "";
var url = params.url;
if (params.query) {
for (const key in params.query) {
str += `${key}=${params.query[key]}&`
}
str = str.slice(0, -1);
}
xhr.open("post", url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.send(str);
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var res = params.isJson ? JSON.parse(xhr.responseText) : xhr.responseText;
params.callback(res);
}
}
}
}
window.onload = function() {
var btn = document.getElementById("btn");
btn.onclick = function() {
// 发送get请求
ajax({
method: "get",
url: "http://localhost/data.php",
query: {
id: 1
},
callback(res) {
var box = document.getElementById("box")
box.innerHTML = `
<h2>编号为:${res.id}</<h2>
<h2>标题为:${res.title}</<h2>
`;
},
isJson: true
})
// ------------------------------------------------------------
// 发送post请求
// ajax({
// method: "post",
// url: "http://localhost/post.php",
// query: {
// id: 2
// },
// callback(res) {
// var box = document.getElementById("box")
// box.innerHTML = `
// <h2>编号为:${res.id}</<h2>
// <h2>标题为:${res.title}</<h2>
// `;
// },
// isJson: true
// })
};
}
</script>
</head>
<body>
<button id="btn">发送请求</button>
<div id="box">
</div>
</body>
data.php
<?php
//设置响应头,解决跨域问题。
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Max-Age:60');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
header('Content-Type:application/json;charset=utf-8');
// 接受浏览器发送过来的数据
$id = $_GET['id'];
// 返回给浏览器的数据
// json_encode 将数组转为json字符串
echo json_encode(array(
'id' => $id,
'title' => 'hello word'
))
?>
post.php
<?php
//设置响应头,解决跨域问题。
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Max-Age:60');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
header('Content-Type:application/json;charset=utf-8');
// 接受浏览器发送过来的数据
$id = $_POST['id'];
// 返回给浏览器的数据
// json_encode 将数组转为json字符串
echo json_encode(array(
'id' => $id,
'title' => 'hello ajax'
))
?>