html模板

<!DOCTYPE html><html lang="en">    <head>        <meta charset="UTF-8">        <meta name="viewport" content="width=device-width, initial-scale=1.0">        <meta http-equiv="X-UA-Compatible" content="ie=edge">        <title>ajax 演示</title>    </head>    <body>        <p>一段文字 1</p>        <script src="./ajax.js"></script>    </body></html>

/data/test.json

{    "name": "zhangsan"}

手写XMLHttpRequest

xhr.readyState

  • 0 - (未初始化)还没有调用send()办法
  • 1 - (载入)已调用send()办法,正在发送申请
  • 2 - (载入实现)send()办法执行实现,曾经接管到全副响应内容
  • 3 - (交互)正在解析响应内容
  • 4 - (实现)响应内容解析实现,能够在客户端调用

xhr.status

  • 2xx - 示意胜利解决申请,如200
  • 3xx - 须要重定向,浏览器间接跳转,如301(永恒重定向),302(长期重定向),304(资源未扭转,应用缓存)
  • 4xx - 客户端申请谬误,如404,403
  • 5xx - 服务器端谬误
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)            )            alert(xhr.responseText)        } else if (xhr.status === 404) {            console.log('404 not found')        }    }}xhr.send(null)

跨域

同源策略

  • ajax申请时,浏览器要求以后网页和server必须同源(平安)
  • 同源:协定、域名、端口,三者必须统一
  • 前端:http://a.com:8080/ ; server:https://b.com/api/xxx(协定、域名、端口均不雷同)

img、css、js可忽视同源策略

  • <img />可用于统计打点,应用第三方统计服务
  • <link /><script>可应用CDN,CDN个别都是外域
  • <script>可实现JSONP

JSONP

  • script 可绕过跨域限度
  • 服务器能够任意拼接数据返回
  • 所以,script就能够取得跨域的数据,只有服务端违心返回
<!DOCTYPE html><html lang="en">    <head>        <meta charset="UTF-8">        <meta name="viewport" content="width=device-width, initial-scale=1.0">        <meta http-equiv="X-UA-Compatible" content="ie=edge">        <title>jsonp 演示</title>    </head>    <body>        <p>一段文字 1</p>        <script>            window.abc = function (data) {                console.log(data)            }        </script>        <script src="http://localhost:8002/jsonp.js?username=xxx&callback=abc"></script>    </body></html>
//jsonp.jsabc(    { name: 'xxx' })

CORS - 服务器设置http header


手写一个繁难的ajax

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 || xhr.status === 500) {                    reject(new Error('404 not found'))                }            }        }        xhr.send(null)    })    return p}const url = '/data/test.json'ajax(url).then(res => console.log(res)).catch(err => console.error(err))