GTS*_*Joe 1 javascript json object
如何将JSON数据嵌入脚本标记中?
<!DOCTYPE html>
<html>
<head>
<script id="data" type="application/json">{org: 10, items:['one','two']}</script>
<script type="text/javascript">
var obj = JSON.parse( document.getElementById('data').value );
console.log( obj );
console.log( obj.org );
</script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我越来越:
未捕获的SyntaxError:位于0的JSON中的意外标记u
<script>
元素不是表单控件.它们没有value
属性(所以.当你读它时,你得到的undefined
是"undefined"
当转换为字符串时,这是无效的JSON).
请改为读取元素内文本节点的内容.
您还需要编写JSON而不是JavaScript对象文字.
"
不'
.<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>
<script type="text/javascript">
var obj = JSON.parse(document.getElementById('data').firstChild.data);
console.log(obj);
console.log(obj.org);
</script>
Run Code Online (Sandbox Code Playgroud)