简体   繁体   中英

how to render html using javascript

I have a javascript engine(using jquery) that needs to render a html which comes as a output from a third party server (REST API). The response contains plain text and occasional html elements like <b>, <p> <br> etc which I want to render as html output. (and not literally as <b>, <p> etc)

Is there a way ?

Here is what I am doing - in pseudo code. Note : I am using blueimp javascript template to generate code.

jQuery.get({
    url: 'someRESTfulURL/id',
    method: 'get',
    success: function(resp) {
      //resp contains html elements like <b> etc
      var data = {title: resp.title, content: resp.content};
      $("#maindiv").html(tmpl("text-tmpl", data)); 
    }
});

<script type="text/x-tmpl" id="text-tmpl">
    <h3>{%=o.title%}</h3>
    <p>{%=o.content%}</p>
</script>

<html><body><div id='maindiv'></div></body></html>

The javascript template is encoding the html characters and hence the problem. Is there a way I can use this template and still render the html chars.

There are two ways you can do this with jQuery:

  1. The first is when you have the response data already, then you can put it into an element like this:

     $("#myElement").html(myData); 
  2. The second is that you could load the data directly into the element:

     $("#myElement").load("http://myurlgoeshere.com/webservice"); 

You have to prevent the escaping of HTML special characters. Try this:

<script type="text/x-tmpl" id="text-tmpl">
    <h3>{%#o.title%}</h3>
    <p>{%#o.content%}</p>
</script>

The difference is just the '#' instead of the '='.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM