【发布时间】:2018-07-15 13:06:11
【问题描述】:
<div>
var arrayContent='<%= myJsonArray %>'
<!--myJsonArray is sent to this ejs file using the render function in
index.js while rendering this ejs file -->
</div>
<script>
var index=0;
function myfunc(){
console.log(arrayContent); /*[object Object],[object Object],[object
Object],[object Object] */
var arrContentJson= JSON.parse(arrayContent);
console.log(arrContentJson[index]); /* Uncaught SyntaxError: Unexpected
token o in JSON at position 1 */
}
</script>
为什么我无法访问解析后的 Json 数组 (arrContentJson) 的内容。如何访问它?
【问题讨论】:
-
myJsonArray可能是一个数组,而不是代表数组的 JSON。 (这里还有<div>标签而不是<script>。)但是,将任意JSON 直接放在<script>标签中是不安全的;您需要使用专门为此目的设计的转义。 (如果你实现了它,你应该通过确保<被转义为\x3c来测试它是否正常工作。) -
最好将调试点放在 var arrayContent='' 并观察变量内容。
-
我认为您提供的
console.log日志不正确。最初arrayContent是一个字符串。它看起来怎样?你得到的错误应该发生在JSON.parse() -
看来不用打
JSON.parse()了。如果您通过 EJS 模板传递 JSON,它应该作为对象文字而不是字符串加载到该脚本中。只需删除<%= myJsonArray %>周围的引号 -
让我困惑的是为什么你在
<div>中包含 JavaScript。
标签: javascript json node.js express ejs