XHR 对象的 open 方法的第三个参数,不写的时候,默认为 true,也就是异步执行。

    1. xhr.open('get', 'data.json');

    这时候,在监听 readyState 变化里面才能够保证数据已经获取成功。

    1. let data = null;
    2. xhr.open('get', 'data.json');
    3. xhr.onreadystatechange(function() {
    4. console.log(readyState); //=> 这里会输出三次,2,3,4,只要这个码变化才会被监听到
    5. if (xhr.readyState == 4 && /^2\d{2}$/.test(xhr.status)) {
    6. data = JSON.parse(xhr.responeText);
    7. }
    8. })
    9. console.log(data); //=> null;

    一般情况下,我们把获取到数据后要执行的事情,封装在一个回调函数里面,然后再 AJAX 异步获取到数据之后,执行这个回调函数。

    1. xhr.onreadystatechange(function() {
    2. console.log(readyState); //=> 这里会输出三次,2,3,4,只要这个码变化才会被监听到
    3. if (xhr.readyState == 4 && /^2\d{2}$/.test(xhr.status)) {
    4. data = JSON.parse(xhr.responeText);
    5. cb(data);
    6. }
    7. })
    8. function cb(data) {
    9. }