xhr --Level 2 的response属性

169 阅读1分钟
    let xhr = new XMLHttpRequest();

    // xhr.responseType = ''; // 默认空,和text一样,表示服务器返回的是文本
   
    // xhr.responseType = 'json'; 
 
    xhr.onload = function () {
      let res = xhr.response; // 因为指定了responseType='json',这里又使用了response接收的结果
      // xhr内部,会自动的 帮我们 JSON.parse(结果)
      console.log(res);
    }
    xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks');
    xhr.send();

如果 指定 xhr.responseType = 'json' 那么 res =xhr.response 是对象格式

如果 指定 xhr.responseType = 'text' 那么 res =xhr.response 是字符串格式

如果 指定 xhr.responseType = 'json' 那么就不能用 res =xhr.responseText来接收了 因为格式不匹配 会报错