AJAX.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import {Promise} from "es6-promise";
  2. /**
  3. * Class with helper methods to handle asynchronous JavaScript requests
  4. */
  5. export class AJAX {
  6. /**
  7. * Retrieve the content of the file at url
  8. * @param url
  9. * @returns {any}
  10. */
  11. public static ajax(url: string): Promise<string> {
  12. let xhttp: XMLHttpRequest;
  13. const mimeType: string = url.indexOf(".mxl") > -1 ? "text/plain; charset=x-user-defined" : "application/xml";
  14. if (XMLHttpRequest) {
  15. xhttp = new XMLHttpRequest();
  16. } else if (ActiveXObject) {
  17. // for IE<7
  18. xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  19. } else {
  20. return Promise.reject(new Error("XMLHttp not supported."));
  21. }
  22. return new Promise((resolve: (value: string) => void, reject: (error: any) => void) => {
  23. xhttp.onreadystatechange = () => {
  24. if (xhttp.readyState === XMLHttpRequest.DONE) {
  25. if (xhttp.status === 200) {
  26. resolve(xhttp.responseText);
  27. } else if (xhttp.status === 0 && xhttp.responseText) {
  28. resolve(xhttp.responseText);
  29. } else {
  30. //reject(new Error("AJAX error: '" + xhttp.statusText + "'"));
  31. reject(new Error("Could not retrieve requested URL"));
  32. }
  33. }
  34. };
  35. xhttp.overrideMimeType(mimeType);
  36. xhttp.open("GET", url, true);
  37. xhttp.send();
  38. });
  39. }
  40. }