[英]How to pass JavaScript variable to g:remoteFunction “update” property?
I have a function in JavaScript that submits a message to a method in a Grails controller and at the same time updates div with myID id. 我在JavaScript中有一个函数,该函数向Grails控制器中的方法提交消息,并同时使用myID id更新div。
function messageKeyPress(field,event,messageBox) {
...
var message = $('#messageBox').val();
<g:remoteFunction action="submitMessage" params="\'message=\'+message" update="myID"/>
...
}
I use it like this: 我这样使用它:
<div id="chatMessages" class="chatMessages"></div>
<input type="text" id="messageBox" class="messageBox" name="message" onkeypress="messageKeyPress(this,event,'#messageBox');"/>
<div id="myID">
I would like that function to be reusable being able to update different divs. 我希望该功能可重用,能够更新不同的div。
I tried: 我试过了:
onkeypress="messageKeyPress(this,event,'#messageBox', '#myID');"
and in JavaScript: 在JavaScript中:
function messageKeyPress(field,event,messageBox, myID) {
...
<g:remoteFunction action="submitMessage" params="\'message=\'+message" update="${myID}"/>
But that didn't work. 但这没有用。 My question is how to pass a JavaScript variable to Grails g:remoteFunction "update" property.
我的问题是如何将JavaScript变量传递给Grails g:remoteFunction“更新”属性。
I suggest you to use jQuery instead. 我建议您改用jQuery。 It is bundled by default to Grails projects.
默认情况下,它捆绑在Grails项目中。 As a result, you'll get a neat separation between javascript code and gsp view logic.
结果,您将在javascript代码和gsp视图逻辑之间得到清晰的区分。 For instance, application.js might look like this:
例如,application.js可能如下所示:
(function($) {
$('.messageBox').on('keypress', function () {
...
var params = {message: $(this).val()};
var url = $(this).data('url');
var target = $(this).data('target');
$.post(url, params, function(response) {
$(target).html(response);
});
...
});
})(jQuery);
and your view file: 和您的视图文件:
<input type="text" id="messageBox"
class="messageBox" name="message"
data-url="${createLink(action: 'submitMessage')}"
data-target="#myId"/>
<div id="myID"></div>
You should assign a messageBox
css class to every input field you want to have this event listener. 您应该为要具有此事件侦听器的每个输入字段分配一个
messageBox
css类。 And in data-target
attribute of every field you can specify a selector for all divs that should be updated. 在每个字段的
data-target
属性中,您可以为应该更新的所有div指定一个选择器。
jQuery is very easy to learn. jQuery非常易于学习。 http://api.jquery.com/
http://api.jquery.com/
The update
attribute should be set to the ID of the element to be updated, not a selector that matches this element. update
属性应设置为要更新的元素的ID,而不是与此元素匹配的选择器。 In other words, try this: 换句话说,请尝试以下操作:
onkeypress="messageKeyPress(this,event,'#messageBox', 'myID');" // '#' removed from myID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.