I am trying to parse some JSON coming from the server into an object I can use in Javascript. The JSON is saved by the server inside a span. When I click on the action button, it should get the JSON and parse it into an object. Unfortunately, I get an exception. Please see the code:
$(function(){
$("#btn").click(function(elem){
var elem = $("#content");
var html = elem.html();
console.log(html);
var x = JSON.parse(html);
console.log(x);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button id="btn">Action</button>
<br/><br/>
<span id="content">{"test" : "<a href=\"http://cnn.com\">CNN</a> Hello"}</span>
</body>
I also tried it with the content in the span not escaping the ":
<span id="content">{"test" : "<a href="http://cnn.com">CNN</a> Hello"}</span>
Any idea how to solve?
Note for background: this is used inside an angular app which needs to receive the json to init the model.
javascriptat Question whereJSONreturned from server is set ashtmlof#contentelement?<a>meant to display visually inside#content, or is#contenthidden. This means of transferring JSON data is bound to fail, since the original HTML markup gets parsed into a DOM and discarded. The.html()call is not giving you the original markup. It generates it on the fly.htmlof#contentelement? Would suggest using.datasetof element or.data()to store theJSON. You are probably losing exactJSONrepresentation by using.innerHTMLof element to convert back and forth.JSONfrom server? Can you include that portion ofjavascriptat Question?