我已经在我的ModelMap中有一个名为cityLocationCodes的地图。我想访问此地图并根据当前用户选择获取值。
我有这个javascript代码:
<script>
function getCoutryValue(countrySelect) {
var countryValue = countrySelect[countrySelect.selectedIndex].value;
console.log(countryValue)
return countryValue;
}
document.addEventListener('DOMContentLoaded', function () {
var countrySelect = document.getElementById('country');
var countryValue = getCoutryValue(countrySelect);
console.log(countryValue);
#foreach ($location in $cityLocationCodes.get(countryValue))
console.log("$location.name");
#end
});
问题是我无法在foreach循环中真正传递var countryValue以从地图中获取正确的值 - $ cityLocationCodes.get(countryValue) - 它不起作用。
我也尝试过另一种方式 -
document.addEventListener('DOMContentLoaded', function () {
var countrySelect = document.getElementById('country');
var countryValue = getCoutryValue(countrySelect);
console.log(countryValue);
var cities = $cityLocationCodes;
for (i = 0; i < cities.get(countryValue).length; i++) {
console.log(cities.get(countryValue)[i].name);
}
当我在我的Chrome浏览器中打开“sources”时,它会以某种方式看到地图,但后来我得到了Uncaught语法错误。所以问题是:如何从控制器传递的地图中获取值,具体取决于我选择的键?
这里有一个很大的误解。
一旦HTTP请求被发送到服务器并且HTTP响应被发送回浏览器,则在客户端的浏览器中评估Javascript代码。
Velocity代码在服务器上进行评估,同时生成HTTP响应。
所以你不能混合使用Javascript和Velocity变量。
如果要在Javascript事件上从服务器获取特定值,则必须使用Ajax调用。