0

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.

3
  • "Tried converting it into JSON but still not able to access the properties (jsresult.data)." - What did you try? I believe the issue is that jsresult is a String, not a JS object so jsresult.data is like "some string value".data. Commented Jun 23, 2021 at 16:41
  • Yes, jsresult is coming as String. Not sure how to convert it into an object and access its properties. Commented Jun 23, 2021 at 16:44
  • "Not sure how to convert it into an object and access its properties" - You had said "Tried converting it into JSON..." - Can you show what you tried? Commented Jun 23, 2021 at 16:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.