Odinodin
Odinodin

Reputation: 2177

Passing Grails params to Javascript

I want to pass URL parameters used in a GSP to a jQuery-function. I have found a solution that works but my gut tells me using global Javascript variables isn´t a good idea.

GSP - making params.id from Grails available for Javascript as a global variable:

<g:javascript >
    var categoryId = ${params.id}
</g:javascript>

Using this variable in a jQuery-function:

<g:javascript src="views/visual.js"/>

Javascript:

// Call with URL using the global variable defined in the GSP
$.getJSON(
    "../visualJson?id=" + categoryId,
    function (data) {
    // Some code.
});

What is the idiomatic Grails way of doing this?

Upvotes: 0

Views: 4400

Answers (1)

Ahmed Nuaman
Ahmed Nuaman

Reputation: 13211

While not necessarily specific to Grails, why don't you pass the variable into a function? Say:

In "views/visual.js" you have:

var someFunction = function(categoryId)
{
    // Call with URL using the global variable defined in the GSP
    $.getJSON(
        "../visualJson?id=" + categoryId,
        function (data) {
        // Some code.
    });
}

And thus you pass the value by calling the function someFunction('${params.id}') in your app.

Upvotes: 3

Related Questions