"render as JSON" is display JSON as text instead of returning it to AJAX call as expected

Posted by typoknig on Stack Overflow See other posts from Stack Overflow or by typoknig
Published on 2012-10-15T22:14:47Z Indexed on 2012/10/15 23:02 UTC
Read the original article Hit count: 139

Filed under:

I'm navigating to the index action of MyController. Some of the on the index page I'm making an AJAX call back to myAction in MyController. I expect myAction action to return some data as JSON to my AJAX call so I can do something with the data client side, but instead of returning the data as JSON like I want, the data is being displayed as text.

Example of my Grails controller:

class MyController {
    def index() {
        render( view: "myView" )
    }

    def myAction {
        def mapOfStuff = [ "foo": "foo", "bar":]
        render mapOfStuff as JSON
    }
}

Example of my JavaScript:

$( function() {
    function callMyAction() {
        $.ajax({
            dataType: 'json',
            url: base_url + '/myController/myAction',
            success: function( data ) {
                $(function() {
                    if( data.foo ) {
                        alert( data.foo );
                    }
                    if( data.bar ) {
                        alert( data.bar );
                    }
                });
            }
        });
    }
});

What I expect is that my page will render, then my JavaScript will be called, then two alerts will display. Instead the JSON array is displayed as text in my browser window:

{"foo":"foo","bar":"bar"}

At this point the last segment of the URL in my address bar is myAction and not index. Now if I manually enter the URL of the index page and press refresh, all works as expected.

I have half a dozen AJAX calls I do the exact same way and none of them are having problems. What is the deal here?

UPDATE:

I have noticed something. When I set a break point in the index action of MyController and another one in the myAction action, the break point in myAction gets hit BEFORE the break point in index, even though I am navigating to the index. This is obviously closer to the root cause of my problem, but why is it happening?

© Stack Overflow or respective owner

Related posts about grails