Grails, jQuery, AJAX: first introduction

    Add jQuery to Grails


    Actually, there are no problems with AJAX in Grails : controllers can safely return JSON data, GSP pages can use the corresponding auxiliary tags .

    By default, Grails is friends with Prototype JS. However, you can install the jQuery support plugin with a flick of the wrist . JQuery 1.4.x will be installed. Next, we need to declare jQuery as a “JavaScript provider” in Grails. In this case, all Grails built-in tags will start working through jQuery. Add the line to grails-app / Config.groovy : Since we want all the pages of our application to start using jQuery, we immediately add to the main layout file (by default, this

    grails install-plugin jquery





    grails.views.javascript.library="jquery"

    grails-app / views / layouts / main.gsp ) to the HEAD section:

      
        ...
        
        ...
      
    ...
    
    

    Now jQuery will be automatically loaded on each page of the application.

    Writing Something in jQuery


    We have already earned such, for example, designs:

    Nothing here.
    Refresh!

    If you look at it in runtime, you will see that the jQuery.ajax () function is implicitly used .

    Having looked at web-app / js / application.js , we find that the generated (using grails create-app) AJAX indicator code is written for Prototype. The built-in display looks crooked (for my taste), but if you really want it to work, you can rewrite the code in jQuery:

    jQuery (document) .ready (function () {
      jQuery (document) .ajaxStart (function () {
        $ ('# spinner'). show ();
      });
      jQuery (document) .ajaxStop (function () {
        $ ('# spinner'). fadeOut (500);
      });
    });
    

    Writing a controller


    Finally, we write a controller suitable for working with AJAX. For example, return a random number in the form of JSON from the controller:

    def random = {
        def max = params.int ('max')
        render (contentType: "text / json") {
    	rnd = new Random (). nextInt (max)
        }
    }
    

    Here we use the new JSON builder from Grails 1.2.x. The result of the controller will be a JavaScript array of the form {rnd: 34}, which we can use, for example, like this:

    Random number: To generate!


    Here, from a JSON result (which in our case falls into a variable data), a value is selected rndand entered in the text field.

    In parentheses, I note that the "transparency" of replacing one JavaScript provider with another only works until a certain point. As soon as you go beyond the Grails built-in AJAX tags and start using jQuery functions (as in the example above), compatibility with other providers is immediately lost.

    Also popular now: