How to assign file contents into a Javascript var

隐身守侯 提交于 2019-12-25 04:54:51

问题


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 :)


回答1:


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.




回答2:


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;



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/3875833/how-to-assign-file-contents-into-a-javascript-var

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!