Grails has a good integration of Ajax, which describes the use of jquery's Getjson method for asynchronous Ajax transmission.
Steps to use:
- Introduction of jquery (. GSP page introduced Jquery.js)
<script type= "Text/javascript" src= "${resource (dir: ' Assets/js ', File: ' Jquery.js ')}" ></script>
- Add Ajax calling methods in Javascript scripts
function Isproductionnameexist (o) { var productName = "Test"; var mode = "Test"; $.getjson ("Isproductionnameexist", //action in controller {productname:productname, //params pass to Action, you can use ' null ' when no params mode:mode}, function (data) { //* Call-back function when Ajax CA ll complete alert (data.isexist);} ); }
Def isproductionnameexist () { def productName = Params.productname
def mode = Params.mode def status = "Y" def ret = [Isexist:status] render ret as JSON }
<g:textfield name= "name" onblur= "Isproductionnameexist (This)"/>
Problems that may exist:
1. Cannot trigger action in controller
The ID parameter in the params affects, as follows, the id attribute
<g:textfield id= "${xxxinstance.attr}" name= "name" onblur= "Isproductionnameexist (This)"/>
Another grails automatically generated additions and deletions when the page jumps will be implicitly passed the ID, will also cause Ajax can not trigger action
2. Garbled characters
The data in the controller/action to get Ajax is garbled, which is caused by different browsers dealing with Ajax requests. For example: In Ajax calls, IE always uses the client OS default encoding, such as GB2312, and Firefox always uses UTF-8 encoding.
To prevent the browser from encoding the data, the data is encoded with a function before the data is transmitted, and the server decodes the data.
Example:
$.getjson ("Isproductionnameexist", {productname:encodeuricomponent (productName)}, function (data) { }); Def isproductionnameexist () { def productName = Params.productName.decodeURL () def status = "Y" def ret = [ Isexist:status] render ret as JSON }
Using Ajax in Grails