ajax
ajax
- 线上mock数据平台
- ajax事件函数
- xhr.onreadystatechange 状态发生变化触发
- xhr.onload 加载完成后触发
- 取response数据
- xhr.response
- xhr.responseText
- xhr.responseXML
//getvar xhr = new XMLHttpRequest()xhr.open('GET', 'http://api.jirengu.com/weather.php', true)xhr.onload = function(){ if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ //成功了 console.log(xhr.responseText) } else { console.log('服务器异常') }}xhr.onerror = function(){ console.log('服务器异常')}xhr.send()//post var xhr = new XMLHttpRequest() xhr.timeout = 3000 //可选,设置xhr请求的超时时间 xhr.open('POST', '/register', true)
xhr.onload = function(e) { if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ console.log(this.responseText) } } //可选 xhr.ontimeout = function(e) { console.log('请求超时') }
//可选 xhr.onerror = function(e) { console.log('连接失败') } //可选 xhr.upload.onprogress = function(e) { //如果是上传文件,可以获取上传进度 }
xhr.send('username=jirengu&password=123456')fetch
跨域
绕过浏览器的同源策略获取数据
- JSONP
- 是通过 script 标签加载数据的方式去获取数据当做 JS 代码来执行 提前在页面上声明一个函数,函数名通过接口传参的方式传给后台,后台解析到函数名后在原始数据上「包裹」这个函数名,发送给前端。换句话说,JSONP 需要对应接口的后端的配合才能实现。
- CORS 后端添加声明,允许哪些域使用我的数据。
- postMessage
- 本地谷歌浏览器临时解决跨域
- 属性>目标>输入 —disable-web-security —user-data-dir=C:\MyChromeDevUserData