javascriptgrailsgroovygsp

How to access returned object from groovy controller in JS file


I am trying to access the returned object from grrovy controller into my javascript code.

Here's the code.

Groovy Controller:

def result = [
               data     : 'data',
               status   : 'success',
            ]
[result: result]

GSP file:

<g:hiddenField name="result" value="${result}" />

JS file:

var jsresult =  $("#result").val();
console.log(jsresult);
console.log(jsresult.data);

Here's the console output:

{data=data, status=success}
undefined

Looks like some issue with formatting but not able to find out the root cause. Tried converting it into JSON but still not able to access the properties (jsresult.data).

Please let me know how I can resolve this and let me know if any alternate way of passing data from groovy controller to JS code.

Thanks.


Solution

  • First, make sure your result is being encoded a proper JSON:

    <g:hiddenField name="result" value=${result as JSON}" /> 
    

    Then parse it in javascript:

    var jsresult = JSON.parse($("#result").val());
    

    You'll get an object back that you can interact with as you expect.

    As far as other ways to do this: there are quite a few, but for simple and arbitrary data transfer to a static page, this is probably the simplest. If you're using ajax requests you can avoid having to place the JSON-encoded data on your page at all, but from what you included here that does not appear to be the case.