Ajax: js向服务器请求数组,实现异步请求局部刷新。
ajax请求步骤:
- 创建XMLHttpRequest异步对象
var xhr = new XMLHttpRequest()
- 创建一个新的http请求,并制定当前请求方式,url,以及验证方式
xhr.open(methods,url,async)
//methods:请求方式有get post head delete put五中,常用的是put post
//url:请求地址,相对路径或者绝对路径
//async:异步或者同步 fasle同步 true异步
- 如果是post请求需要设置请求头
xhr.setRequestHeader('contentType','application/x-www-form-urlencoded')
- 发送请求
xhr.send() //如果请求为post请求需要要send()中传入参数
- 接收服务器返回数据,判断数据是否正常返回
xhr.onreadyStateChange = function(){
if(xhr.status == 200 && xhr.readyState === 4){
xhr.responseText
}
}
xhr.readyState请求状态
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完成,且响应已就绪
xhr.status状态码:
200:请求成功
403: 服务器拒绝请求
404: 服务器找不到请求的网页
504:请求超时
500: 服务器内部错误