将数组从 Java 传递到 javascript (MVC)
Passing array to javascript from Java (MVC)
我有一个 MVC 应用程序,我在其中设置模型对象中的整数 ArrayList。
在 JSP 中,我将此数组设置为隐藏字段 - 该数组包含 [1, 2]
<input type="hidden" id="matchingLevels" value="${matchForm.matchingLevels}"/>
然后在js中我想用这个作为数组
var matchingLevels = $('#matchingLevels').val();
console.log("Form section to display: " + matchingLevels);
for (var i = 0; i < matchingLevels.length; i++) {
console.log("matchiong level: " + matchingLevels[i]);
}
但这是控制台日志中显示的内容(它循环遍历每个字符而不是数组的值)
Form section to display: [1, 2]
matchiong level: [
matchiong level: 1
matchiong level: ,
matchiong level:
matchiong level: 2
matchiong level: ]
如何转换为 javacript 数组并对其进行循环?
解析一下:
JSON.parse(matchingLevels)
通过使用 JSON.Parse(yourListOfValues) 作为对象获取。
var matchingLevels =JSON.parse(matchingLevels);
console.log("Form section to display: " + matchingLevels);
for (var i = 0; i < matchingLevels.length; i++) {
console.log("matchiong level: " + matchingLevels[i]);
}
我有一个 MVC 应用程序,我在其中设置模型对象中的整数 ArrayList。
在 JSP 中,我将此数组设置为隐藏字段 - 该数组包含 [1, 2]
<input type="hidden" id="matchingLevels" value="${matchForm.matchingLevels}"/>
然后在js中我想用这个作为数组
var matchingLevels = $('#matchingLevels').val();
console.log("Form section to display: " + matchingLevels);
for (var i = 0; i < matchingLevels.length; i++) {
console.log("matchiong level: " + matchingLevels[i]);
}
但这是控制台日志中显示的内容(它循环遍历每个字符而不是数组的值)
Form section to display: [1, 2]
matchiong level: [
matchiong level: 1
matchiong level: ,
matchiong level:
matchiong level: 2
matchiong level: ]
如何转换为 javacript 数组并对其进行循环?
解析一下:
JSON.parse(matchingLevels)
通过使用 JSON.Parse(yourListOfValues) 作为对象获取。
var matchingLevels =JSON.parse(matchingLevels);
console.log("Form section to display: " + matchingLevels);
for (var i = 0; i < matchingLevels.length; i++) {
console.log("matchiong level: " + matchingLevels[i]);
}