AJAX.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * Class with helper methods to handle asynchronous JavaScript requests
  3. */
  4. export class AJAX {
  5. /**
  6. * Retrieve the content of the file at url
  7. * @param url
  8. * @returns {any}
  9. */
  10. public static ajax(url: string, timeout: number = 9000): Promise<string> {
  11. let xhttp: XMLHttpRequest;
  12. const mimeType: string = url.indexOf(".mxl") > -1 ? "text/plain; charset=x-user-defined" : "application/xml";
  13. if (XMLHttpRequest) {
  14. xhttp = new XMLHttpRequest();
  15. } else if (ActiveXObject) {
  16. // for IE<7
  17. xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  18. } else {
  19. return Promise.reject(new Error("XMLHttp not supported."));
  20. }
  21. xhttp.timeout = timeout;
  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 " + xhttp.status));
  32. }
  33. }
  34. };
  35. xhttp.ontimeout = (e) => {
  36. // For IE and node
  37. reject(new Error("Server request Timeout"));
  38. };
  39. xhttp.overrideMimeType(mimeType);
  40. xhttp.open("GET", url, true);
  41. xhttp.send();
  42. });
  43. }
  44. }