XMLHttpRequest
//get
const xhr = new XMLHttpRequest()
xhr.open('GET','/api',false)//false同步
xhr.onreadystatechange=function(){//img.onlad=function(){}
if(xhr.readyState===4){
if(xhr.status===200){
console.log(JSON.parse(xhr.responseText))
alert(xhr.responseText)
}else{
console.log('其他情况')
}
}
}
xhr.send(null)
//post
const xhr = new XMLHttpRequest()
xhr.open('POST','/api',true) //true异步
xhr.onreadystatechange=function(){//img.onlad=function(){}
if(xhr.readyState===4){
if(xhr.status===200){
console.log(JSON.parse(xhr.responseText)) //json格式变对象
alert(xhr.responseText)
}else{
console.log('其他情况')
}
}
}
const postData={
userName:'zhangsan',
password:'xxx'
}
xhr.send(JSON.stringify(postData))//发送要用字符串
状态码-readyState
- 0:(未初始化)还没调用send()方法
- 1:(载入)已调用send()方法,正在发送请求
- 2:(载入完成)sebd()方法执行完成,已经接收到全部响应内容
- 3:(交互)正在解析响应内容
- 4:(完成)响应内容解析完成,可以在客户端调用
状态码-status
- 2xx:表示成功处理请求,如200
- 3xx:需要重定向,浏览器直接跳转,如301(永久重定向) 302(临时重定向) 304
- 4xx:客户端请求错误,如404 403
- 5xx:服务器端错误
什么是同源策略
- ajax请求时,浏览器要求当前网页和server必须同源(安全)
- 同源:协议,域名,端口,三者必须一致
加载图片 css js 可无视同源策略
<img src=跨域的图片地址/>
<link src=跨域的css地址/>
<script src=跨域的js地址/></scrpt>
<img/>
可用于统计打点,可使用第三方统计服务
<link/><script>
可使用CDN,CDN一般都是外域
<script>
可实现JSONP
跨域
- 所有的跨域,都必须经过serve端允许和配合
- 未经server端允许就实现跨域,说明浏览器有漏洞,危险信号
解决跨域的常见的方式 JSONP和CORS
- JSONP
<script>
可以绕过跨域限制- 服务器可以任意动态拼接数据返回
- 所有,
<script>
就可以获取跨域的数据,只要服务端愿意返回
<script>
window.callback = function (data) {
console.log(data)
}
</script>
<script src="http://localhost:8002/jsonp.js?username=xxx&callback=abc"></script>
<!-- 返回callback({name:'xxx'}) data={name:'xxx'}-->
用jq实现JSONP
- CORS-服务器设置http header
实际项目中ajax的常用插件
- jquery.ajax ($.ajax)
- fetch
- axios 对XMLHttpRequest的封装