开发者

Access list items from JavaScript

开发者 https://www.devze.com 2023-04-10 22:00 出处:网络
I want to access model items by index from JavaScript into a Play Framework template: <script type=\"text/javascript\" charset=\"utf-8\">

I want to access model items by index from JavaScript into a Play Framework template:

<script type="text/javascript" charset="utf-8">
    window.onload = function()
    {
        var cl = ${colors.size()};
        int i = 0;
        for (i=0;i<cl;i++)
        {
            labels = labels + "${colors.name.get(i).escapeJavaScript().raw()}";
        }
    }
</script>

My problem is that this loop throws an exception:

IndexOutOfBoundsException : Index: 12, Size: 4

Nota 0: model = Color.

Nota 1: the size is 4.

Nota 2: if I test with a fixed number instead 开发者_Python百科of variable i it is ok, but this is not what I need.

Cannot get why it does not work.


You try to use Groovy inside a Javascript loop which is wrong.

Remember your Groovy code (inside ${}) is evaluated by the Play templating on the server side and result of an HTML page returned to the client, and the Javascript is evaluated on client side (by the browser, not on your server).

maybe you want to do something like :

<script type="text/javascript" charset="utf-8">
window.onload = function()
{
    labels = [#{list colors.name}"${_.escapeJavaScript().raw()}"#{if !_isLast},#{/if}#{/list}];
}

which is still dangerous if you don't understand what it does,

prefer using a simple AJAX request and the renderJSON method for dynamic loadings.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号