Q1:使用XMLHttpRequest来封装 AJAX,同时使用 Promise 进行封装:

    1. function getJSON(url) {
    2. return new Promise((resolve, reject) => {
    3. // 1.创建 xhr 实例
    4. const xhr = new XMLHttpRequest();
    5. // 2.注册相关事件回调函数
    6. xhr.onreadystatechange = function() {
    7. if(xhr.readyState !== 4) return
    8. if(xhr.status === 200 || xhr.status === 304) {
    9. resolve(xhr.responseText)
    10. } else {
    11. reject(new Error(xhr.responseText))
    12. }
    13. /*
    14. switch(xhr.readyState) {
    15. case 0:
    16. console.log("请求未初始化");
    17. break;
    18. case 1:
    19. console.log("OPENED");
    20. break;
    21. case 2:
    22. console.log("HEADERS_RECEIVED");
    23. break;
    24. case 3:
    25. console.log("LOADING");
    26. break;
    27. case 4:
    28. if(xhr.status === 200 || xhr.status === 304) {
    29. resolve(xhr.responseText)
    30. }
    31. console.log("DONE")
    32. break;
    33. default:
    34. reject(new Error(xhr.responseText))
    35. }
    36. */
    37. }
    38. xhr.ontimeout = function(){} // 超时执行的回调函数
    39. xhr.onerror = function(){} // 网络请求出错执行的回调函数
    40. // 3.打开请求
    41. xhr.open("GET", url, true) // 创建一个 GET 请求,采用异步
    42. // 4.配置参数
    43. xhr.timeout = 3000
    44. xhr.setRequestHeader("Content-Type": "application/json")
    45. // 5.发送请求
    46. xhr.send()
    47. })
    48. }