简体   繁体   中英

Velocity template - using java script variables in velocity foreach

I have so I have this map in my ModelMap called cityLocationCodes . I want to access this map and get value depending on current user select.

I have this javascript code:

<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

});

The thing is I can't really pass var countryValue inside foreach loop to get right value from the map - $cityLocationCodes.get(countryValue) - it does not work.

I also tried the other way around -

    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);
    }

It does somehow see the map when I open "sources" in my chrome browser, but then I get Uncaught syntax error . So the question is: how can i get values from the map passed by a controller depending on a key that is in my select?

There is a big misunderstanding, here.

The Javascript code is evaluated in the browser, on the client side, once the HTTP request has been sent to the server and the HTTP response sent back to the browser.

The Velocity code is evaluated on the server, while generating the HTTP response.

So you cannot mix Javascript and Velocity variables.

You will have to resort to making Ajax calls if you want to fetch specific values from the server on a Javascript event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM