Friday, September 11, 2015

How to Load Text into Html from a File

When creating a "static" page with some informational text, it may be helpful to enable admins to replace the text without editing the main html page.


This can be done by using an Ajax request to load a text file or preformatted html file into the innerHTML of an element.


JQuery.ajax can be used to fetch the file then write the contents to the page.



$.ajax({
    url:'textFile.html',
    type:'html',
    success:function(data){
        $('#elementId')[0].innerHTML = '<pre>'+ data + '</pre>';
    }
});


with this approach, the textFile can be marked up with plain html tags and it will work without the need to escape them.


One thing to note about using this approach is that the file should be available via the web server and at a path relative to the host site, this would avoid additional configurations - just let the same web server serve up the textFile.


Basically, in this way you can have a wrapper and put the content into the wrapper however. Sort of a way to do an SPA.


I'd you'd like, set the pre CSS to wrap the lines. As an alternate to appending pre tags, you could style the parent element.


More information about that -
http://www.w3schools.com/cssref/pr_text_white-space.asp

No comments:

Post a Comment