<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>AJAX结构</title>
</head>
<body>
<script>
var xhr = new XMLHttpRequest(); // 1、 构建一个XMLHttpRequest实例对象
xhr.onreadystatechange = function () { // 4、 使用事件监听状态是否成功
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText))
}
}
xhr.open(type, url, true); // 2、 配置请求
xhr.send(); // 3、 发送
</script>
</body>
</html>
一、构建一个XMLHttpRequest 实例对象,得到 xhr 对象
var xhr = new XMLHttpRequest();
二、配置请求、连接后台
xhr.open(type, url, true);
type:请求方式 ;分为 GET 和 POST 请求 (可根据需求使用其中一个,详细可参考它们之间的区别);
url: 接口的地址;(这个是有后台提供)
这里需要注意的是:get方式传值:在URL路径后加 ? 和数据 (如:a=1&b=2); post方式传值:不在路径URL上写数据而在 send() 上发送数据 xhr.send( "username=" + name );使用send传输数据,需要先设置编码方式:xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
true:异步(一起做)异步执行一般都有一个回调函数或监听函数,当异步完成之后执行;
false:同步(一件一件的做);
三、发送数据
xhr.send();
四、使用事件监听状态是否成功
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText))
}
}
把onreadystatechange放在open之前可以多监听一个状态 1 的状态;
readystate 请求状态 : 0 请求为初始化; 1 服务连接已建立; 2 请求已接收; 3 请求处理中; 4 请求已完成,且响应已结束;
所以为什么会在监听这里进行判断 xhr.readyState == 4
status HTTP 状态码: 1xx 消息 ; 2xx 成功 (200); 3xx 缓存 ; 4xx 客户端错误,404请求失败 请求所希望得到的资源未被在服务器上发现; 5xx 服务器错误
所以也会在监听这里进行判断 xhr.status == 200; 是否成功