ajax.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. let Ajax = function () {
  2. }
  3. Ajax.prototype = {
  4. constructor: Ajax,
  5. get: function (url) {
  6. return new Promise((resolve, reject) => {
  7. let xhr = new XMLHttpRequest();
  8. xhr.open('GET', url, true);
  9. xhr.onreadystatechange = function() {
  10. // readyState == 4说明请求已完成
  11. if (parseInt(xhr.readyState) === 4) {
  12. if (parseInt(xhr.status) === 200 || parseInt(xhr.status) === 304) {
  13. resolve(xhr.responseText);
  14. } else {
  15. reject(xhr);
  16. }
  17. }
  18. };
  19. xhr.send();
  20. })
  21. },
  22. post: function (url, data, contentType) {
  23. return new Promise((resolve, reject) => {
  24. let xhr = new XMLHttpRequest();
  25. xhr.open("POST", url, true);
  26. // 添加http头,发送信息至服务器时内容编码类型
  27. if (!contentType || contentType !== 'formdata' ) {
  28. !contentType && (contentType = 'application/x-www-form-urlencoded');
  29. xhr.setRequestHeader('Content-Type', contentType);
  30. }
  31. xhr.onreadystatechange = function() {
  32. if (parseInt(xhr.readyState) === 4) {
  33. if (parseInt(xhr.status) === 200 || parseInt(xhr.status) === 304) {
  34. resolve(JSON.parse(xhr.responseText));
  35. } else {
  36. reject(JSON.parse(xhr.responseText));
  37. }
  38. }
  39. };
  40. xhr.send(data);
  41. })
  42. }
  43. }
  44. export default Ajax;