grails中很好的集成了Ajax,这里介绍利用Jquery的 getJSON方法进行Ajax异步传输。
使用步骤:
<script type="text/javascript" src="${resource(dir: ‘assets/js‘, file: ‘jquery.js‘)}"></script>
   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 call 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)"/>
可能存在的问题:
1. 无法触发controller中action
params中的id参数会影响, 如下,id属性
<g:textField id="${xxxInstance.attr}" name="name" onblur="isProductionNameExist(this)"/>
另grails自动生成的增删查改页面跳转时会隐式传id,也会导致ajax无法触发action
2. 乱码
controller/action中拿到ajax传过去的数据都是乱码,由不同浏览器对于ajax请求不同的处理方式造成。例如:在Ajax调用中,IE总是采用客户端操作系统默认编码,如GB2312,而Firefox总是采用utf-8编码。
为了避免浏览器对数据进行编码,在数据传送前先用函数对数据进行编码,server拿到数据后再解码。
例子:
 $.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
  }
原文:http://www.cnblogs.com/chenyongjun/p/4456249.html