-3

How to load HTML file from another HTML file using javascript and not JQuery?

I have seen couple of examples using jquery .load function but I need to know how can we load html file using simple javascript.

Max
  • 1,334
  • 5
  • 16
  • 34
  • Please share what you have tried so far – Harsha Venkataramu May 28 '13 at 09:31
  • 3
    They use jQuery because you need to do an AJAX call and jQuery gives you an easy way to do that. If you don't do that, you will have to build your own AJAX call. http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery you have an example here. – DaGLiMiOuX May 28 '13 at 09:32
  • @harsha Have seen jquery using like this. $("head").load("sample.html"); But don't know how javascript uses it. – Max May 28 '13 at 09:34
  • Jquery is "simple javascript" it's just a library that uses javascript underneath. Why can't you just reference the jquery files? – Liam May 28 '13 at 09:37
  • All.. This is a typical situation that not all my clients will use jquery in there pages. I will be added the jqeury script in the loading HTML. From then only I can get access to jquery. @DaGLiMiOuX: Thanks for the reply. That actually can be explained how to get the file. Few changes from that script works for me – Max May 28 '13 at 09:42

2 Answers2

1

jQuery load function is a simple wrapper around XMLHttpRequest object that loads content using the specified url and places it into the matched element. So, your example $("head").load("sample.html"); loads the content of the sample.html page and places it into the head tag.

In order to do this without jQuery you need to create XMLHttpRequest object directly. The exact code depends on the browsers you are targeting, but you can find a lot of examples online. A good place to start is w3schools.com

Sergey Rybalkin
  • 3,004
  • 22
  • 26
0

You should have a look at: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started and on readyState == 4 the request is completed. A successful request results in a HTTP 200 message:

if (httpRequest.readyState === 4) {
  if (httpRequest.status === 200) {

These are the guarding clauses, which check the result subsequentially. After both checks pass, you could append your result (httpRequest.responseXML) to the DOM.

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43