当前位置:   article > 正文

es6 AJAX封装_es6 封装ajax请求

es6 封装ajax请求
  1. class Ajax {
  2. constructor(xhr) {
  3. xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
  4. this.xhr = xhr;
  5. }
  6. send(options) {
  7. let xhr = this.xhr;
  8. let ajax = {
  9. type: options.type || 'GET',
  10. url: options.url || '',
  11. async: options.async || 'true',
  12. dataType: options.dataType || 'json',
  13. data: options.data || ''
  14. };
  15. return new Promise((resolve, reject) => {
  16. let dataList = [];
  17. for (let key in ajax.data) {
  18. dataList.push(key + '=' + ajax.data[key])
  19. }
  20. let dataStr = dataList.join("&");
  21. if (ajax.type === "get" || ajax.type === "GET") {
  22. console.log(dataStr);
  23. ajax.url = dataStr ? ajax.url + "?" + dataStr : ajax.url;
  24. console.log(ajax.url);
  25. xhr.open(ajax.type, ajax.url, ajax.async);
  26. xhr.send();
  27. }
  28. if (ajax.type === "post" || ajax.type === "POST") {
  29. xhr.open(ajax.type, ajax.url, ajax.async);
  30. xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  31. if (ajax.data) {
  32. xhr.send(ajax.data);
  33. } else {
  34. xhr.send();
  35. }
  36. }
  37. xhr.onreadystatechange = () => {
  38. if (xhr.readyState === 4) {
  39. if (xhr.status >= 200 && xhr.status < 400) {
  40. const data = JSON.parse(xhr.response);
  41. resolve(data);
  42. console.log(data);
  43. } else if (xhr.status >= 400) {
  44. const data = JSON.parse(xhr.response);
  45. console.log(data);
  46. reject(new Error(xhr.status || 'Server if sail'));
  47. }
  48. }
  49. }
  50. })
  51. }
  52. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/148237
推荐阅读
相关标签
  

闽ICP备14008679号