#### 1.手写简易Ajax

//Ajax - GET请求
const xhr = new XMLHttpRequest();
// true 为异步,false为同步
xhr.open('GET', 'URL', false)
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.response);
}
}
}
xhr.send(null)

//Ajax - POST请求
const post = new XMLHttpRequest();
// true 为异步,false为同步
post.open('POST', 'URL', true);
post.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// TODO
}
}
}
const postData = {
userName: 'user',
passWord: 'xxxx'
}
post.send(JSON.stringify(postData))

2.Ajax状态码

##### xhr.readyState

> 0 -(未初始化)还没有调用send()方法
>
> 1 -(载入)已调用send()方法,正在发送请求
>
> 2 -(载入完成)send()方法执行完成,已经接收到全部响应内容
>
> 3 -(交互)正在解析响应内容
>
> 4 -(完成)响应内容解析完成,可以在客户端调用

##### xhr.status

> 2Xx - 表示成功处理请求,如200
> 3Xx - 需要重定向,浏览器直接跳转,如301、302、304
> 4Xx - 客户端请求错误,如404、403
> 5Xx - 服务器端错误

3.同源策略与跨域

- ajax请求时,浏览器要求当前网页和server必须同源(安全)
- 同源:协议、域名、端口,三者必须一致
- 加载图片css js可无视同源策略

> 1. 可以用于统计打点,使用第三方统计服务
> 2. 可以和script 用于加载CDN,CDN一般都是外域
> 3. 可实现JSONP前端跨越解决方案

- 所有的跨域,都必须经过server端允许和配合
- 未经server端允许就实现跨域,说明浏览器有漏洞,危险信号

4.跨越解决方案 - JSONP

实现原理: