javascript - How to embed json with html control character entites in the html and let js consume that? -
i have use case need embed json in html , let javascript read it. example this:
<head></head> <body> <div id="foo">{"foo": "bar
"}</div> <script> var = json.parse(document.getelementbyid('foo').innerhtml); console.log(a); </script> </body> </html> notice json has carriage return in 
 , because html parser convert entities original character, inner html javascript gets contain literal newline character, breaks json parse function call.
the solutions have:
- wrap content in cdata
- wrap content in script tag (this produce error parser saying syntax not valid seems working regardless)
question is: these approaches okay? if these not best practice, approach should used here?
encode & entity &. , use textcontent raw content, without re-encoding & entity.
var = json.parse(document.getelementbyid('foo').textcontent); alert(json.stringify(a)); console.log(a); <div id="foo">{"foo": "bar&#xc;"}</div>
Comments
Post a Comment