Grails - 从Javascript方法调用控制器和渲染模板

use*_*124 2 javascript jquery grails controller

如何从Javascript方法将调用映射到Grails控制器?我看到一个使用PHP的方法,但没有使用grails:

function getSelected(checkList)
        {
            var idList = new Array();
            var loopCounter = 0;
            //find all the checked checkboxes
            jQuery("input[name=" + checkList + "]:checked").each
            (
              function()
              {
                //fill the array with the values
                idList[loopCounter] = jQuery(this).val();
                loopCounter += 1;
              }
            );

            //call here

        }
Run Code Online (Sandbox Code Playgroud)

编辑:

${remoteFunction(controller:"person", action:"runThroughAll", params:"[ids:idList]")}
Run Code Online (Sandbox Code Playgroud)

JSa*_*ger 6

所以,我觉得你在这里要问的有两件事.我要解决他们两个问题.首先,如何从JavaScript获取调用grails控制器的URL?在我的GSP页面中(我在我的主要布局中做了但是无论如何),我喜欢这个小技巧:

<script>
myapp.url.root = "<g:resource dir='' file='' />" + "/";
</script>
Run Code Online (Sandbox Code Playgroud)

这将为您提供应用程序的基础,无论它在何处部署.然后,您可以使用JavaScript构建网址:

myurl = myapp.url.root +"path/to/controller"

然后使用该url进行jQuery ajax调用.

然后确保您的控制器已设置为响应您刚刚表达的任何URL模式.

第二个问题似乎是"如何发回HTML片段"?

在控制器本身内部,从请求中获取参数,使用它来找出你需要的任何东西,然后渲染gsp,传入你创建的模型.它看起来像这样:

def show() {
   def data = [hypothesis : metadataService.getHypothesis(params.id) as JSON]
   render(view:"create", model:data)
}
Run Code Online (Sandbox Code Playgroud)

然后在jQuery中,您的成功处理程序将获得返回响应作为参数,然后您可以检查/操作/添加到dom.

希望所有这些都有意义.如果我掩饰某些东西或者没有回答你提出的问题,请告诉我.

编辑:为了将来参考,这里是重写的javascript方法,我们在聊天中到达:

function getSelected(checkList){ 
var idList = $("input[name='" + checkList + "']:checked").map(function(){ return $(this).val(); }); 

$.ajax({ 
url: "/path/to/controller", 
type:"POST", 
data:{ids:JSON.stringify(idList)} 
success:mySuccessFunction 
}); 
}
Run Code Online (Sandbox Code Playgroud)