How to store Json string in a hidden input field. Well, I could do it programmatically, but something wrong with escaping. Since my string is moderately long, it is hard to escape " char for all the names. Please explain how it works programmatically (phase 1), as the console output looks same.
[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]test2.html:21
[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]
test2.html:22
PASSED PHASE 1
jquery.min.js:16Uncaught SyntaxError: Unexpected end of input
thanks,
bsr.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE HTML><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<input type="hidden" id="jsondata" />
<input type="hidden" id="jsondata2" value="[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]"/>
<script >
$(document).ready(function() {
myItems = [{"X":0,"Y":0,"W":0,"H":500},
{"X":358,"Y":62,"W":200,"H":500}]
console.log(JSON.stringify(myItems));
$("#jsondata").val(JSON.stringify(myItems));
console.log(document.getElementById("jsondata").value);
console.log("PASSED PHASE 1");
var obj = jQuery.parseJSON($("#jsondata2").val());
console.log(obj.length);
console.log("PASSED PHASE 2");
});
</script>
</body>
</html>
Edit:
the following code works.. not sure whether it is correct. so will mark a good explanation as answer. thanks.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE HTML><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<input type="hidden" id="jsondata" />
<input type="hidden" id="jsondata2" value='[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]'/>
<script >
$(document).ready(function() {
myItems = [{"X":0,"Y":0,"W":0,"H":500},
{"X":358,"Y":62,"W":200,"H":500}]
console.log(JSON.stringify(myItems));
$("#jsondata").val(JSON.stringify(myItems));
console.log(document.getElementById("jsondata").value);
console.log("PASSED PHASE 1");
var obj = jQuery.parseJSON($("#jsondata2").val());
console.log($("#jsondata2").val());
console.log(obj[0].H);
console.log("PASSED PHASE 2");
});
</script>
</body>
</html>