当前位置:   article > 正文

用ES6封装AJAX函数,支持GET/POST

ajax封装 用于发送get请求es6
  1. function Ajax({
  2. type = "GET",
  3. url = "",
  4. async = true,
  5. params = {},
  6. responseType = "text",
  7. contentType = "application/x-www-form-urlencoded", //xhr.setRequestHeader("Content-Type",option.contentType);
  8. done = () => {},
  9. fail = () => {}
  10. }) {
  11. type = type.toUpperCase();
  12. params = formatParams(params);
  13. //创建xhr对象 step1
  14. const xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
  15. xhr.responseType = responseType;
  16. //接收 step3
  17. xhr.onreadystatechange = () => {
  18. if (xhr.readyState === 4) {
  19. const status = xhr.status;
  20. if (status >= 200 && status < 300) {
  21. done(response);
  22. } else {
  23. fail(status);
  24. }
  25. }
  26. }
  27. //发送 step2
  28. if (type === "GET") {
  29. xhr.open("GET", url + "?" + params, async);
  30. xhr.send(null);
  31. } else if (type === "POST") {
  32. xhr.open("POST", url, async);
  33. //设置表单提交时的内容类型
  34. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  35. xhr.send(params);
  36. }
  37. }
  38. function formatParams(params) {
  39. const arr = [];
  40. for (let name in params) {
  41. arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(params[name]));
  42. }
  43. arr.push(("_=" + Math.random()).replace(".", ""));
  44. return arr.join("&");
  45. }
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/148141
推荐阅读
相关标签
  

闽ICP备14008679号