ajax.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import Observer from './observer';
  2. /**
  3. * Perform an ajax request
  4. *
  5. * @param {Options} options Description
  6. *
  7. * @returns {Object} Observer instance
  8. */
  9. export default function ajax (options) {
  10. const instance = new Observer();
  11. const xhr = new XMLHttpRequest();
  12. let fired100 = false;
  13. xhr.open(options.method || 'GET', options.url, true);
  14. xhr.responseType = options.responseType || 'json';
  15. xhr.addEventListener('progress', e => {
  16. instance.fireEvent('progress', e);
  17. if (e.lengthComputable && e.loaded == e.total) {
  18. fired100 = true;
  19. }
  20. });
  21. xhr.addEventListener('load', e => {
  22. if (!fired100) {
  23. instance.fireEvent('progress', e);
  24. }
  25. instance.fireEvent('load', e);
  26. if (200 == xhr.status || 206 == xhr.status) {
  27. instance.fireEvent('success', xhr.response, e);
  28. } else {
  29. instance.fireEvent('error', e);
  30. }
  31. });
  32. xhr.addEventListener('error', e => instance.fireEvent('error', e));
  33. xhr.send();
  34. instance.xhr = xhr;
  35. return instance;
  36. }