ajax设置ua,ajax常见问题总结【面试回顾】

html模板

ajax 演示

一段文字 1

/data/test.json{

"name": "zhangsan"

}

手写XMLHttpRequest

xhr.readyState0 - (未初始化)还没有调用send()方法

1 - (载入)已调用send()方法,正在发送请求

2 - (载入完成)send()方法执行完成,已经接收到全部响应内容

3 - (交互)正在解析响应内容

4 - (完成)响应内容解析完成,可以在客户端调用

xhr.status2xx - 表示成功处理请求,如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必须同源(安全)

同源:协议、域名、端口,三者必须一致

img、css、js可无视同源策略可用于统计打点,使用第三方统计服务

可使用CDN,CDN一般都是外域

可实现JSONP

JSONPscript 可绕过跨域限制

服务器可以任意拼接数据返回

所以,script就可以获得跨域的数据,只要服务端愿意返回

jsonp 演示

一段文字 1

window.abc = function (data) {

console.log(data)

}

//jsonp.js

abc(

{ name: 'xxx' }

)

CORS - 服务器设置http header

手写一个简易的ajaxfunction 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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值