tags:

views:

67

answers:

4

ok, this is simple, but I kinda need a noob's help.

I'd like to do something simple: To assign an HTML file contents to a JS var, and then to pass this html code into a page element using the innerHTML property.

This can be done easily with HtmlHTTPRequest, however, i'm not sure what is the exact code i should use.

here's what I'd like to achieve:

var foo = contents_of_an_html_file (file.html)
document.getElementById('preview').innerHTML = foo;

Would be happy for your enlightenment :)

A: 

While I'm not sure if you're using jQuery (it doesn't seem you are if you're using straight xhr), it may be worth looking into the load ajax method that they provide. It does exactly that.

Bit Destroyer
Some say, jQuery will one day cure cancer :)
Marko
Sure, I'd just prefer not to load jQuery from page weight considerations.
noob
A: 

You cannot easily get the contents of a file on a local file system for security reasons. However, if your page is located at a webserver (say, http://example.com/), this will work:

function file_get_contents(url){
   try{
      var x = new XMLHttpRequest();
      x.open('get', url, true);
      x.send(null);
      if(x.status != 200){// return nothing if the status code is not 200 OK, e.g. the page is not found
         return '';
      }
      return x.responseText;
   }
   catch(e){// failed to retrieve contents
      return '';
   }
}
var foo = file_get_contents('file.html');
document.getElementById('preview').innerHTML = foo;
Lekensteyn
Thanks, i'll try that!
noob
A: 

You should consider using an iframe to do the get. Then you can use JavaScript to get the contents of the iframe. If you position the iframe correctly then you may not need the JavaScript at all.

Mike
I don't like this approach (for fetching the contents of a file). It takes more time as any attached resources has to be downloaded and loaded. (the cache might be used, but you cannot rely on that)
Lekensteyn
A: 

Here is a function with an iframe, no JS lib, no ajax.

function getFile(src, target){
    var ifr = document.createElement('IFRAME');
    ifr.onload = function(e){
        target.innerHTML = 
           (ifr.contentDocument||ifr.contentWindow.document).body.innerHTML;
        document.body.removeChild(ifr);
        ifr = null;
    };
    ifr.src = src;
    ifr.style.display = 'none';
    document.body.appendChild(ifr);
}

And to use it:

getFile('file.html', document.getElementById('preview'));

You can get other elements of the page than the body tag if needed.

Mic
(see my comment on Mikes answer too) This works only if the page has a very basic setup (no scripts). Using `.innerHTML`, any scripts in `file.html` won't be evaluated on the current page.
Lekensteyn
It works well in our web app. As I said, other elements thand the body tag can be loaded from the page. In fact we load HTML, CSS and JS this way. And it's fast.
Mic