Ajax是一种在无需重新加载整个网页情况下,能够局部更新。
创建Ajax的步骤
1.创建Ajax对象,new一个XMLHttpRequest的实例化对象
let xhr = new XMLHttpRequest();- 2.连接到服务器
open(方法,文件名,同步异步) //xhr.open('get', 'abc.txt', true)
获取文件的数据一定要使用异步true、
参数一:post/get
参数二:请求的文件名
参数三:同步(false) 异步(true)
setTimeout是一个异步操作
- 3.发送请求:
xhr.send(); - 4.接收和监听返回值
//onreadystatechange就是用来监听readyState值的变化的
xhr.onreadystatechange = function () {
console.log(xhr.responseText)
//xhr.responseText 通过ajax请求获得的数据
}
<button onclick="getData()">获取用户信息</button>
<div id="userInfo"></div>
<script>
function getData() {
let userInfo = document.getElementById('userInfo');
let xhr = new XMLHttpRequest();//创建对象
//XMLHttpRequest()用于与服务器交互
xhr.open('get', 'data.json', true);//'data.json地址文件名
xhr.send();
xhr.onreadystatechange = function () {
//onreadystatechange就是用来监听readyState值的变化的
if (xhr.readyState == 4) {
//开始解析响应内容
let obj = JSON.parse(xhr.responseText);
//xhr.responseText 通过ajax请求获得的数据
let str =
'<h1>姓名:' + obj.name + '</h1>' +
'<h1>年纪:' + obj.age + '</h1>' +
'<h1>城市:' + obj.city + '</h1>' +
'<h1>汽车:</h1>';
if (obj.flag) {
//这个flag加进去的用意,如控制某个标签的隐藏或显示等功能
for (var i = 0; i < obj.arrList.length; i++) {
str += '<h1>' + obj.arrList[i].car + '</h1>';
//arrList实现List接口的,底层采用数组实现
}
}
userInfo.innerHTML = str;
- status 响应状态码
凡是为200开头都表示请求成功304 从http请求中的缓存拿来的数据404 not found 找不到地址 地址写错了 未找到页面,★多数前端问题403 表示没有权限status 为500 表示服务端代码错误