0

What is the JavaScript equivalent of $('content').load('page.html'); I am trying to load content in another page into my div but I cannot find a method for plain old JavaScript.

uSeRnAmEhAhAhAhAhA
  • 2,527
  • 6
  • 39
  • 64

5 Answers5

2

The good old JavaScript:

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

var myRequest = new XMLHttpRequest();           //XMLHttpRequest is how you do it
myRequest.onreadystatechange = function(e){
    if(myRequest.readyState == 4 && myRequest.status == 200){
        var data = myRequest.responseText;               //returned data
        document.querySelector("div").innerHTML = data;  //not safe but whatever
    }
};
myRequest.open("get", "url here", true);
myRequest.send();

It is always better to do it with plain JavaScript first before using those fancy jQuery one-method-takes-care-of-everything-for-you methods.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
1

Your question has two parts:

  1. Grabbing some content on a server from the client
  2. Pushing that content into a div.

For part one, see this thread for instructions on using XMLHTTPRequest():

HTTP GET request in JavaScript?

For part two, as for populating the div, it's this simple:

document.getElementById('content').innerHTML = 'someContent';

Note that you may want to scrub your content before populating the div depending on the source of the page you are requesting, as using JS to populate a div with raw HTML is an attack vector that hackers might try to exploit.

Community
  • 1
  • 1
Robert Munn
  • 778
  • 7
  • 12
0

Have you tried taking a look at using iframes? http://www.w3schools.com/tags/tag_iframe.asp

Richard
  • 1,138
  • 1
  • 6
  • 11
  • I thought about it but they're considered bad practice nowadays, aren't they? – uSeRnAmEhAhAhAhAhA Apr 18 '14 at 21:37
  • 1
    It really depends on what situation you're using it for. Could you go into more detail on what type of content you're trying to load? Is it just from another page within your domain? Do you care about CSS? – Richard Apr 18 '14 at 21:42
  • 1
    @Spike - It can be good or bad depending on how you use it. There is a question on SO discussed this topic: http://stackoverflow.com/questions/362730/are-iframes-considered-bad-practice – Derek 朕會功夫 Apr 18 '14 at 21:47
0

It's called an XML HTTP Request (XHR). See the docs here.

willlma
  • 7,353
  • 2
  • 30
  • 45
0

As you can see from the source code here, jQuery's load() function calls the ajax() function to load the external html.

Under the hood, the ajax() function uses XMLHttpRequest which is how you would retrieve the file using vanilla JavaScript.

jshanley
  • 9,048
  • 2
  • 37
  • 44