Reputation: 11205
I am trying to render a json response from grails controller action. Here is my code:
render ([message:"voila Sent Successfully!"]) as JSON
But in the gsp, it is rendering like:
['message':'Email Sent Successfully!']
Above text is actually a string(as its typeof in jquery ajax call gives a string in the success event handler), so how do I render it as a JSON?
I am using grails 2.4.5 and the JSON class is actually grails.converters.JSON (not grails.converters.deep.JSON)
Upvotes: 2
Views: 732
Reputation: 1048
I'd like to expose another answer, which avoids an issue like one that I already found in IE. Some older IE versions could try to download your JSON as a file.
Generate your JSON response from your collection/map and then render it as a string, so:
import grails.converters.JSON
def YourService
def yourControllerNameHere(){
def result = YourService.generatesYourResult(),
resultJSON = result as JSON
render resultJSON.toString()
}
Then, in your ajax, parse this string as JSON-object using jQuery, that is:
$.ajax({
url : WEB_ROOT + 'yourUrl/yourControllerNameHere',
type : 'post',
dataType: 'text',
success : function(resultStr) {
var result = $.parseJSON(resultStr);
alert('this is your response type: ' + (typeof result));
// this is your response type: object
}
});
Upvotes: 1
Reputation: 4373
Just do as
render ([message:"voila Sent Successfully!"] as JSON )
i.e inserting as JSON
within parentheses.
Upvotes: 4