一、服务器端渲染和前后端分离(前端渲染)
1.1. 服务器端渲染
- 早期的网页都是通过后端渲染完成的,这也被称之为服务器端渲染
- 具体步骤为:客户端向服务器端发起请求,服务器向数据库查询数据,拿到数据之后,再把数据给渲染HTML的模板,最后再把模板组装起来返回给客户端
- 服务器端渲染的弊端
- 当用户点击页面中的某个按钮向服务器发送请求时,页面本质上只是需要改变一些数据,可此时服务器却需要将整个整个页面进行重绘,再将其返回给浏览器。这就会给网络宽带带来一些不必要的开销,并且太占用服务器资源
1.2. 前后端分离(前端渲染)
- 前端渲染的实现主要是依赖于Ajax(异步的JavaScript和XML)
- Ajax最吸引人的地方就是它的异步特性,也就是说它可以在不重新加载页面的情况下与服务器通信,接受并使用服务器发来的数据
- 具体步骤为:前端向前端服务器(这个服务器中存储的基本都是一些静态的资源,所以也被称之为前端服务器)发送请求拿到静态HTML页面、JavaScript脚本等文件,然后在执行JavaScript脚本时,JS脚本会向后端服务器发送Ajax请求去获取数据,拿到数据之后,再通过JavaScript脚本对页面进行一个渲染
- 前端渲染的弊端
- 不利于SEO优化,并且页面在首次加载时,等待的时间会比较长,再就是安全性比后端渲染会差一些
二、Ajax的封装
2.1. 基本封装
function zdAjax(url) {
const xhr = new XMLHttpRequest()
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response)
}
}
xhr.responseType = "json"
xhr.open("get", url)
xhr.send()
}
zdAjax("http://123.207.32.32:8000/home/multidata")
2.2. 接收各个参数
function zdAjax(url, {
method = "get",
data = {},
timeout = 10000,
success,
failure,
headers
} = {}) {
const xhr = new XMLHttpRequest()
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
success && success(xhr.response)
} else {
failure && failure({code: xhr.status, message: xhr.statusText})
}
}
xhr.responseType = "json"
if (method.toUpperCase() === "GET") {
const queryParamKeys = Object.keys(data)
const paramString = queryParamKeys.map(item => {
return `${item}=${data[item]}`
}).join("&")
xhr.open(method, url + "?" + paramString)
xhr.send()
} else {
xhr.open(method, url)
const headerParamsKeys = Object.keys(headers)
headerParamsKeys.forEach(item => {
xhr.setRequestHeader(item, headers[item])
})
xhr.send(JSON.stringify(data))
}
}
zdAjax("http://123.207.32.32:1888/02_param/postjson", {
success(res) {
console.log("res:", res)
},
failure(err) {
console.log("err:", err)
},
method: "post",
data: {
name: "kobe",
age: 32
},
headers: {
"Content-type": "application/json"
}
})
2.3. 返回Promise进行异步操作
- 将所有的操作都放在promise中,那么就可以不用再传递success和failure了
function zdAjax(url, {
method = "get",
data = {},
timeout = 10000,
headers
} = {}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response)
} else {
reject({
code: xhr.status,
message: xhr.statusText
})
}
}
xhr.responseType = "json"
xhr.timeout = timeout
if (method.toUpperCase() === "GET") {
const queryParamKeys = Object.keys(data)
const paramString = queryParamKeys.map(item => {
return `${item}=${data[item]}`
}).join("&")
xhr.open(method, url + "?" + paramString)
xhr.send()
} else {
xhr.open(method, url)
const headerParamsKeys = Object.keys(headers)
headerParamsKeys.forEach(item => {
xhr.setRequestHeader(item, headers[item])
})
xhr.send(JSON.stringify(data))
}
})
}
zdAjax("http://123.207.32.32:1888/02_param/get", {
data: {
name: "kobe",
age: 18
}
}).then(res => {
console.log("res:", res)
})