1.GET请求
//1. 创建AJAX对象
const xhr = new XMLHttpRequest();
//2. 设置请求方法和url
xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&C=300&=300');
//3. 发送
xhr.send();
//4. 事件绑定 处理服务端返回的结果
/*
on:when:当...时候
readystate: 是XHR对象中的一个属性,表示状态:
0(未初始化)
1(open方法调用完毕)
2(send方法调用完毕)
3(服务端返回部分结果)
4(服务端返回所有结果)
change:改变
*/
xhr.onreadystatechange = function(){
//作判断,是4(服务端返回了所有的结果)才处理数据
if(xhr.readyState === 4){
//判断响应状态码:200 404 403 401 500
//2XX 都是成功
if(xhr.status >= 200 && xhr.status < 300){
//处理服务端响应结果: 行 头 空行(咱不管) 体
//1. 处理响应行
// console.log(xhr.status);//状态码
// console.log(xhr.statusText);//状态字符串
// //2. 所有响应头
// console.log(xhr.getAllResponseHeaders());
// //3. 响应体
// console.log(xhr.response)
//设置result的文本
result.innerHTML = xhr.response +','+ xhr.status;
}else{
}
}
}
2.POST请求
//1.创建Ajax对象
const xhr = new XMLHttpRequest();
//2.初始化,请求体
xhr.open('POST','http://127.0.0.1:8000/server');
//设置请求头
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('name','atGuiGu');
// 请求体内容类型
//3.发送
xhr.send('a=100&b=200&c=300');
// xhr.send('a:100&b:200&c:300');
//4.绑定响应事件
xhr.onreadystatechange=function (){
if(xhr.readyState === 4) {
if(xhr.status >=200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
}
3.JSON
const xhr = new XMLHttpRequest();
//设置响应体数据类型
xhr.responseType = 'json';
xhr.open('GET','http://127.0.0.1:8000/json-server');
xhr.send();
//4.绑定响应事件
xhr.onreadystatechange=function (){
if(xhr.readyState === 4) {
if(xhr.status >=200 && xhr.status < 300) {
console.log(xhr.response);
//手动对数据转行
// let data = JSON.parse(xhr.response);
//自动装 设置接受数据为JSON数据类型
result.innerHTML = xhr.response.name;
}
}
}
4.取消请求
//取消请求
btns[1].addEventListener('click',function(){
xhr.abort();
})
5.超时异常
//1. 创建AJAX对象
const xhr = new XMLHttpRequest();
//超时设置 2s
xhr.timeout = 2000;
//超时回调
xhr.ontimeout = function (){
alert('网络异常,请稍后重试');
}
//网络异常回调
xhr.onerror = function (){
alert('网络异常~!');
}
//2. 设置请求方法和url
xhr.open('GET','http://127.0.0.1:8000/ie?a=100&');
//3. 发送
xhr.send();
//4. 事件绑定 处理服务端返回的结果
/*
on:when:当...时候
readystate: 是XHR对象中的一个属性,表示状态:
0(未初始化)
1(open方法调用完毕)
2(send方法调用完毕)
3(服务端返回部分结果)
4(服务端返回所有结果)
change:改变
*/
xhr.onreadystatechange = function(){
//作判断,是4(服务端返回了所有的结果)才处理数据
if(xhr.readyState === 4){
//判断响应状态码:200 404 403 401 500
//2XX 都是成功
if(xhr.status >= 200 && xhr.status < 300){
//处理服务端响应结果: 行 头 空行(咱不管) 体
//1. 处理响应行
// console.log(xhr.status);//状态码
// console.log(xhr.statusText);//状态字符串
// //2. 所有响应头
// console.log(xhr.getAllResponseHeaders());
// //3. 响应体
// console.log(xhr.response)
//设置result的文本
result.innerHTML = xhr.response +','+ xhr.status;
}else{
}
}
}