ajax.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * http请求封装
  3. * @param opt
  4. */
  5. /*-------------------Ajax start--------------------*/
  6. function ajax(options) {
  7. return new Promise((resolve, reject) => {
  8. options = options || {};
  9. options.type = (options.type || "GET").toUpperCase();
  10. options.dataType = options.dataType || "json";
  11. var params = formatParams(options.data);
  12. var xhr;
  13. //创建 - 第一步
  14. xhr = new XMLHttpRequest();
  15. //连接 和 发送 - 第二步
  16. if (options.type == "GET") {
  17. xhr.open("GET", options.url + "?" + params, true);
  18. xhr.send(null);
  19. } else if (options.type == "POST") {
  20. xhr.open("POST", options.url, true);
  21. //设置表单提交时的内容类型
  22. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  23. xhr.send(params);
  24. }
  25. //接收 - 第三步
  26. xhr.onreadystatechange = function () {
  27. if (xhr.readyState == 4) {
  28. var status = xhr.status;
  29. if (status >= 200 && status < 300 || status == 304) {
  30. resolve(xhr.responseText, xhr.responseXML)
  31. } else {
  32. reject(status)
  33. }
  34. }
  35. }
  36. })
  37. }
  38. //格式化参数
  39. function formatParams(data){
  40. var arr = [];
  41. for (var name in data) {
  42. arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
  43. }
  44. arr.push(("v=" + Math.random()).replace(".",""));
  45. return arr.join("&");
  46. }
  47. /*-------------------Ajax end-------------------*/
  48. export default ajax