Search code examples
jqueryajaxdomplaintext

Fetch text but insert as html, jQuery Ajax


So I want to build an ajax website that fetches pages using api requests which will return the results in plain-text but I want jQuery to load it into the page as HTML is that possible?


Solution

  • I use the following to get content in a specific div from an HTML document and append it to an element. In the example, #treatment is the id of the div in the external document:

    var content = 'external_page.html';
    
    $.get(content, function(data){
         var el = $('<div>').html(data).find('#treatment');
         el.hide().appendTo('#content_frame_right').fadeIn(500);
    });
    

    The hide is there to enable the fadeIn, if you don't want the fadeIn, then just use:

    el.appendTo('#content_frame_right');
    

    You can use the simple PHP library called html2text to convert the HTML doc to text on import. See https://github.com/mtibben/html2text

    Or for a JavaScript solution you could use htmlparser2