简体   繁体   中英

Display HTML tags as HTML in AJAX response

I have controller method:

def do_it
   @result = "some <b>another</b>"

   respond_to do | format |  
        format.js {render :layout => false}  
   end
end

And do_it.js.erb:

$( "#in" ).html("<b>hello</b> <br /> <%= @result %>");

When I call this method I'll get 'hello' as bold text, but 'another' as ordinary text with tags in my browser.

在此处输入图片说明

I need to hide all html tags and display 'another' as bold text. How can I fix it ?

<%= %> escapes the HTML code by default. You can prevent it from doing this by:

$( "#in" ).html("<b>hello</b> <br /> <%= raw @result %>");

or

@result = "some <b>another</b>".html_safe()

I don't really know much about ruby, but I came on this post that might be relevant to your problem:

1- rails: how to html encode/escape a string? is there a built-in?

2- How do I encode/decode HTML entities in Ruby?

I think you should html-encode your original string

@result = "some <b>another</b>"

then html-decode it when displaying it. Good Luck

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