How can I do javascript to print a json object (sent from ruby) without interpreting it as html?

ruby / sinatra serving "object.to_json" for ajax request:

... content_type :json adam.to_json end #--> #<Human:0x10aa540 @x=68, @y=24, @name="Adam", @age=50> 

js with jquery:

 ... $("#player").html(data); ... 

as a result, the div is filled only with the symbol "#".

console.log (data) shows:

 #<Human:0x10aa540 @x=68, @y=24, @name="Adam", @age=50> 

So, I assume that this is happening because "<" and other characters are interpreted in html. How can I avoid this and show the object on the web page, how does it appear on the debug console?

thanks

+4
source share
2 answers

In case this helps:

 data.replace(/\</gi,"&lt;"); 

jsfiddle

+1
source

You can ask the browser to leave the HTML for you by adding it to the temporary block and extracting the escaped content. This way you guarantee that all HTML markup will be escaped, not just > and < :

 var temp_div = document.createElement('div'); // Create temporary div temp_div.appendChild(document.createTextNode(data)); // Insert data as Text data = temp_div.innerHTML; // Get Text escaped 

jsFiddle

+1
source

Source: https://habr.com/ru/post/1443915/


All Articles