前端面试知识整理——AJAX
题目:
- 手写一个简易的AJAX
//手写一个简易的 ajax
//不推荐
function ajax(url, successFn) {
const xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
successFn(xhr.responseText)
}
}
}
xhr.send(null)
}
//promise
function ajax(url) {
const p = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText))
} else if (xhr.status === 404) {
reject(new Error('404 not found'))
}
}
}
xhr.send(null)
})
return p
}
ajax('./data/test.json')
.then((result) => {
console.log(result)
})
.catch((err) => {
console.log(err)
})
- 跨域的常用实现方式:JSONP CROS
知识点:
- XMLHttpRequest
- 状态码
- 跨域:同源策略,跨域解决方案
XMLHttpRequest
//get
const xhr = new XMLHttpRequest()
xhr.open('GET', './data/test.json', true) //true异步请求
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText))
} else {
console.log('error')
}
}
}
xhr.send(null)
//post
const xhr = new XMLHttpRequest()
xhr.open('POST', '/login', true)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText))
}
}
}
const postData = {
userName: 'zhangsan',
age: 13,
}
xhr.send(JSON.stringify(postData))
xhr.readyState
- 0 (未初始化),还没有调用send方法
- 1(载入)已调用send方法,正在发送请求
- 2 (载入完成)send()方法执行完成,已经接收到全部响应内容
- 3(交互)正在解析响应内容
- 4 (完成)响应内容解析完成,可以在客户端调用
xhr.status
- 2xx 表示成功处理请求,如200
- 3xx 需要重定向,浏览器直接跳转,如301,302,304(301永久重定向,302临时重定向,304服务器端资源未改变,可直接使用客户端未过期的缓存)
- 4xx 客户端请求错误,403-禁止访问,404-无法找到文件
- 5xx 服务器端错误
跨域
- 什么是跨域(同源策略)
- JSONP
- CORS(服务端支持)
同源策略
- ajax请求时,浏览器要求当前网页和server必须同源(安全)
- 同源:协议、域名、端口,三者必须一致
- 前端:http://a.com:8080/; server:https://b.com/api/xxx
加载图片 css js可无视同源策略
- img src= 跨域的图片地址
- link href= 跨域的css地址
- script src=跨域的js地址
应用:
- img可用于统计打点,可使用第三方统计服务
- link/script可使用CDN,CDN一般都是外域
- script可实现JSONP
跨域
- 所有的跨域,都必须经过server端允许和配合
- 未经server端允许就实现跨域,说明浏览器有漏洞,危险信号
JSONP
- 访问http://imooc.com/,服务端一定返回一个html文件吗(不是,如果这样的话,那么得到的仅仅是个静态文件)
- 服务端可以任意动态拼接数据返回,只要符合HTML格式要求
- 同理于 < script src=‘http://imooc.com/getData.js’ >
point:
- < script >可绕过跨域限制
- 服务器可以任意动态拼接数据返回
- 所以,< script >就可以获得跨域的数据,只要服务端愿意返回
CORS-服务器设置 http header
//第二个参数填写允许跨域的域名城,不建议直接写‘*’
response.addHeader("Access-Control-Allow-Origin", "http://localhost:8002");