Advertisement
Guest User

Untitled

a guest
Mar 17th, 2018
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. $('#div').load('/somePage');
  2.  
  3. var request = new XMLHttpRequest();
  4.  
  5. request.open('GET', '/somepage', true);
  6.  
  7. request.onload = function() {
  8. if (request.status >= 200 && request.status < 400) {
  9. var resp = request.responseText;
  10.  
  11. document.querySelector('#div').innerHTML = resp;
  12. }
  13. };
  14.  
  15. request.send();
  16.  
  17. fetch('/somepage')
  18. .then(function(response) {
  19. return response.text();
  20. })
  21. .then(function(body) {
  22. document.querySelector('#div').innerHTML = body;
  23. });
  24.  
  25. /*
  26. * Replicates the functionality of jQuery's `load` function,
  27. * used to load some HTML from another file into the current one.
  28. *
  29. * Based on this Stack Overflow answer:
  30. * https://stackoverflow.com/a/38132775/3626537
  31. * And `fetch` documentation:
  32. * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
  33. *
  34. * @param {string} parentElementId - The ID of the DOM element to load into
  35. * @param {string} htmlFilePath - The path of the HTML file to load
  36. */
  37. const loadHtml = function(parentElementId, filePath) {
  38. const init = {
  39. method : "GET",
  40. headers : { "Content-Type" : "text/html" },
  41. mode : "cors",
  42. cache : "default"
  43. };
  44. const req = new Request(filePath, init);
  45. fetch(req)
  46. .then(function(response) {
  47. return response.text();
  48. })
  49. .then(function(body) {
  50. // Replace `#` char in case the function gets called `querySelector` or jQuery style
  51. if (parentElementId.startsWith("#")) {
  52. parentElementId.replace("#", "");
  53. }
  54. document.getElementById(parentElementId).innerHTML = body;
  55.  
  56. });
  57. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement