如何将调用从 Javascript 方法映射到 Grails Controller ?我看到一个使用 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
}
编辑:
${remoteFunction(controller:"person", action:"runThroughAll", params:"[ids:idList]")}
最佳答案
所以,我觉得您在这里要问两件事。我要对付他们两个。首先,如何获得从 JavaScript 调用 grails Controller 的正确 URL?在我的 GSP 页面中(我在主布局中这样做,但无论如何),我喜欢做这个小技巧:
<script>
myapp.url.root = "<g:resource dir='' file='' />" + "/";
</script>
这将为您提供应用程序部署的基本根目录。然后,您可以在 JavaScript 中构建您的 URL:
myurl = myapp.url.root + "path/to/controller"
然后使用该 url 进行 jQuery ajax 调用。
然后确保您的 Controller 已设置为响应您刚刚表达的任何 URL 模式。
第二个问题似乎是“我怎样才能发回 HTML 片段”?
在 Controller 本身内部,从请求中获取参数,使用它来确定您需要的任何内容,然后渲染 gsp,传入您创建的模型。它看起来像这样:
def show() {
def data = [hypothesis : metadataService.getHypothesis(params.id) as JSON]
render(view:"create", model:data)
}
然后在 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
});
}
关于javascript - Grails - 从 Javascript 方法调用 Controller 和呈现模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9639068/