[英]How do I pass a JSON object from JSP to Javascript?
I have a variable for myInitState that is initialized within a controller that is then passed to a jsp view. 我有一个myInitState变量,该变量在控制器内初始化,然后传递给jsp视图。
<script>
myInitFunction({
myInitState: '${myInitState}',
componentName: 'myCompName',
divId: 'divId'
});
</script>
However by using '${myInitState}'
, in my Javascript I notice I get a string of "{...}" when debugging in browser. 但是,通过在我的Javascript中使用
'${myInitState}'
,我注意到在浏览器中进行调试时会得到一个字符串“ {...}”。 Is it possible to pass the object as json and have it be recognized as such or would I have re-parse the object within myInitFunction
? 是否可以将对象作为json传递并将其识别为JSON,或者我将在
myInitFunction
重新解析该对象?
In order to take advantage of string interpolation, you need to use backticks 为了利用字符串插值的优势,您需要使用反引号
`${myInitState}`
`$ {myInitState}`
You will then want to parse the string inside the function using JSON.parse(someString)
然后,您将需要使用
JSON.parse(someString)
解析函数内部的字符串。
Updating answer here: A couple of things I had left out of my question due to my misunderstanding: - myInitState is a Map of <String,Object>
- The values of the map could be already escaped JSON blobs. 在这里更新答案:由于我的误解,我没有考虑以下几点:-myInitState是
<String,Object>
Map-该Map的值可能已经转义了JSON Blob。
In this case the flow was from Server to client, so in order to convert the map into a JSON blob correctly I would need to do something like this in JSP: 在这种情况下,流程是从服务器到客户端的,因此为了正确地将地图转换为JSON Blob,我需要在JSP中执行以下操作:
<script>
var jsonBlob = {
<c:forEach items="${myInitState}" var="state" varStatus="loop">
"${state.key}": ${state.value} ${not loop.last ? ',' : ''}
</c:forEach>
};
</script>
However, a better approach, and what I went with, would be to just do conversion in the controller itself where myInitState is constructed. 但是,一种更好的方法以及我所采用的方法是只在构造myInitState的控制器本身中进行转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.