作者:
    作者:xl

    1. /**
    2. * 1. 创建 XmlHttpRequest 对象
    3. * 2. 初始化
    4. * 3. 发送消息
    5. * 4. 接收消息
    6. */
    7. function ajax(options) {
    8. // 创建一个 xhr 实例
    9. const xhr = new XMLHttpRequest();
    10. // 初始化请求
    11. xhr.open('GET', options.url);
    12. // 接收请求
    13. // 当 readyState 属性发生变化时
    14. xhr.onreadystatechange = function() {
    15. if(xhr.readyState === 4) {
    16. const status = xhr.status;
    17. if (status === 200) {
    18. options.success?.(xhr.response);
    19. } else {
    20. options.fail?.(xhr.response);
    21. }
    22. }
    23. }
    24. // 接收错误
    25. xhr.onerror = function(e) {
    26. options.fail?.(e);
    27. }
    28. // 指定响应类型
    29. xhr.responseType = 'json';
    30. // 设置请求头
    31. // xhr.setRequestHeader();
    32. // 发起请求
    33. xhr.send();
    34. }
    35. ajax({
    36. url: 'https://segmentfault.com/gateway/article/1190000017176090/related',
    37. success(data) {
    38. console.log('data', data);
    39. },
    40. fail(data) {
    41. console.log('err', data);
    42. },
    43. })

    作者:奥兰度

    1. function ajax(url, method) {
    2. let xhr = new XMLHttpRequest()
    3. xhr.open(method, url)
    4. xhr.send()
    5. }

    作者:gochri

    1. const getJSON = function (url = 'test.html',method = 'GET',[...settings]) {
    2. return new Promise((resolve, reject) => {
    3. const xhr = new XMLHttpRequest();
    4. xhr.open(method, url, false);
    5. // settings
    6. xhr.setRequestHeader("Content-Type", "application/json");
    7. xhr.onreadystatechange = function () {
    8. if (xhr.readyState !== 4) return;
    9. if (xhr.status === 200 || xhr.status === 304) {
    10. resolve(xhr.responseText);
    11. } else {
    12. reject(new Error(xhr.responseText));
    13. }
    14. };
    15. xhr.send();
    16. });
    17. };

    作者:
    作者: