创建ajax发送请求的基本步骤:
get请求:
//1 创建xhr对象
const xhr = new XMLHttpRequest();
//2 初始化设置请求方式和url
//?a=1&b=2 跟在url后面 ?后面是参数(get请求参数跟在url后面)
//xhr.open('get','http://127.0.0.1:8000/server?a=1&b=2');
xhr.open('get','http://127.0.0.1:8000/server');
//3 发送
xhr.send();
//4 事件绑定 处理服务端返回的结果
//readystate 是 xhr 对象中的属性,表示状态
//有五种 0(未初始化) 1(open方法调用完毕) 2(send方法调用完毕) 3(服务端返回了部分结果) 4(服务端返回了所有结果)
//change 改变的时候触发 会触发四次
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){//服务端返回了所有结果
//判断响应状态码 200 404 403 401 500 (2xx 2开头都表示成功)
if(xhr.status >= 200 && xhr.status < 300){
//拿到响应结果,在这里可以对结果进行处理
console.log(xhr.status);//状态码
console.log(xhr.statusText);//状态字符串
console.log(xhr.getAllResponseHeaders);//所有响应头
console.log(xhr.response);//响应体
}
}
}
post请求: 与get请求差不多,只是参数是在send()方法里传递
//1 创建xhr对象
const xhr = new XMLHttpRequest();
//2 初始化设置请求方式和url
xhr.open('post','http://127.0.0.1:8000/server');
//设置请求头
xhr.setRequestHeader('Context-Type','application/x-www-form-urlencoded');
//3 发送
//post请求的参数是在send()方法里设置的 发送的数据可以是任意字符 但是通常情况采用键值对形式
xhr.send('a=1&b=2');
//xhr.send('a:1&b:2');
//xhr.send('1325463');
//4 事件绑定 处理服务端返回的结果
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
//拿到响应结果,在这里可以对结果进行处理
console.log(xhr.status);//状态码
console.log(xhr.statusText);//状态字符串
console.log(xhr.getAllResponseHeaders);//所有响应头
console.log(xhr.response);//响应体
}
}
}