1. 通过回调函数的方式封装 Ajax

  1. // callback
  2. const Ajax = ({
  3. method = 'get',
  4. url = '/',
  5. data,
  6. async = true
  7. }, callback) => {
  8. let xhr = new XMLHttpRequest()
  9. xhr.onreadystatechange = () => {
  10. if (xhr.readyState === 4 && xhr.status === 200) {
  11. let res = JSON.parse(xhr.responseText)
  12. callback(res)
  13. }
  14. }
  15. xhr.open(method, url, async)
  16. if (method === 'get') {
  17. xhr.send()
  18. }
  19. if (method === 'post') {
  20. let type = typeof data
  21. let header
  22. if (type === 'string') {
  23. header = 'application/x-www-form-urlencoded'
  24. }
  25. else {
  26. header = 'application/json'
  27. data = JSON.stringify(data)
  28. }
  29. xhr.setRequestHeader('Content-type', header)
  30. xhr.send(data)
  31. }
  32. }
  33. Ajax.get = (url, callback) => {
  34. return Ajax({
  35. url
  36. }, callback)
  37. }
  38. Ajax.get('http://localhost:3000/getData', (res) => {
  39. console.log(res)
  40. })
  41. }

2. 通过 promise 封装

  1. const Ajax = function(url) {
  2. return new Promise((resolve, reject) => {
  3. let xhr = null;
  4. if (window.XMLHttpRequest) {
  5. xhr = new XMLHttpRequest();
  6. } else {
  7. xhr = new ActiveXObject("Microsoft.XMLHTTP");
  8. }
  9. xhr.onreadystatechange = () => {
  10. if (xhr.readyState === 4 && xhr.status === 200) {
  11. let res = JSON.parse(xhr.responseText)
  12. resolve(res)
  13. } else {
  14. reject(xhr.responseText)
  15. }
  16. }
  17. if (method === 'get') {
  18. xhr.send()
  19. }
  20. if (method === 'post') {
  21. let type = typeof data
  22. let header
  23. if (type === 'string') {
  24. header = 'application/x-www-form-urlencoded'
  25. }
  26. else {
  27. header = 'application/json'
  28. data = JSON.stringify(data)
  29. }
  30. xhr.setRequestHeader('Content-type', header)
  31. xhr.send(data)
  32. }
  33. })
  34. }