文章目录
Ajax实现步骤
- 创建ajax对象
let xhr = new XMLHttpRequest()
兼容ie写法
// ActiveXObject('Microsoft.XMLHTTP') IE
// new XMLHttpRequest() 非IE
let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP')
- 设置 请求方式 请求地址
// 请求方式 GET POST ...
// 请求地址 http://xxx.xx/xx
xhr.open("GET",'http://xxx.xx/xx')
- 发送请求
xhr.send()
// post 参数传递 xhr.send(参数)
- 获取响应数据
xhr.onload = function(){ // 接收到响应触发
console.log(xhr.responseText)
}
或者
// 每当 readyState 改变时,就会触发 onreadystatechange 事件。
xhr.onreadystatechange = function(){
// xhr.readyState 0: 请求未初始化 1: 服务器连接已建立 2: 请求已接收 3: 请求处理中 4: 请求已完成,且响应已就绪
// xhr.status 响应状态码
if(xhr.readyState = 4 && xhr.status = 200){
}
}
get请求是不能提交json对象格式数据的,传统网站的表单提交也是不支持json对象格式数据的
get请求示例
// 创建ajax对象
let xhr = new XMLHttpRequest()
// 设置请求方式 和 请求地址 参数age=18&name=xx async 是否异步 默认true
xhr.open('GET','http://localhost:3000/first?&age=18&name=xx',true)
// 发送请求
xhr.send()
// 监听响应 获取响应数据
xhr.onload = function(){
console.log('res',xhr.responseText)
}
post请求示例
// 创建ajax对象
let xhr = new XMLHttpRequest()
// 设置请求方式 和 请求地址
xhr.open('POST','http://localhost:3000/first')
// 设置请求头
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
// 发送请求
xhr.send('age=18&name=xx') // 参数
// 监听响应 获取响应数据
xhr.onload = function(){
console.log('res',xhr.responseText)
}
post请求参数格式
urlencoded格式参数
'age=18&name=xx'
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.send('age=18&name=xx')
json格式参数
{name:'张三'}
xhr.setRequestHeader('Content-Type','application/json')
xhr.send(JSON.stringify({name:'张三'}))
图片
文件
ajax状态码 onreadystatechange
表示ajax请求的过程,ajax对象返回的
在创建ajax对象,配置ajax对象,以及接收完服务端响应数据,这个过程中的每一个步骤都会对应一个数值,这个数值就是ajax状态码。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
xhr.readyState // 获取状态码
监听 状态码 变化
xhr.onreadystatechange = function(){}
示例
let xhr = new XMLHttpRequest()
console.log(xhr.readyState,"已经创建了ajax对象 还未配置") // 0 已经创建了ajax对象 还未配置
xhr.open('POST','http://localhost:3000/first')
console.log(xhr.readyState," 已经配置 还未发送请求") // 1 已经配置 还未发送请求
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.onreadystatechange = function(){
// 2 已经发送请求
// 3 已经接收到服务端部分响应数据
// 4 数据接收完成 请求完成
console.log(xhr.readyState)
if(xhr.readyState == 4){
console.log(xhr.responseText)
}
}
xhr.send('age=18&name=xx') // 参数
onload/onreadystatechange兼容性
Ajax错误处理
网络畅通,服务器能接收请求,服务端返回的结果不是预期结果。xhr.status
http状态码:表示请求的处理结果,服务器返回的
可以判断服务端返回的响应状态码,分别进行处理。xhr.status获取http状态码
xhr.status
// 成功 200
网络畅通,服务器没有接收请求, 服务端返回404
检查请求地址是否错误。
网络畅通,服务器能接收请求,服务端返回500
服务端错误
网络中断,请求无法发送到服务器
网络中断无法触发 onload 事件
会触发xhr对象的onerror事件,在onerror事件处理函数中对错误进行处理
xhr.onerror = function(){
console.log('网络中断,无法发送')
}
低版本IE浏览器的缓存问题
问题:在低版本IE浏览器中,Ajax请求有严重的缓存问题,即在请求地址不发生变化的情况下,只有第一次请求会真正发送到服务器端。后续的请求都会从浏览器的缓存中获取结果,即使服务器的数据更新了,客户端依然拿到的是缓存中的旧数据。
解决:在请求地址后面加上参数,保证每一次请求参数的值不同。
xhr.open("GET","http://xxx.xx?t="+Math.random())