【问题标题】:Javascript functions not working in GrailsJavascript 函数在 Grails 中不起作用
【发布时间】:2017-07-12 14:31:07
【问题描述】:

我很难理解为什么以下代码不起作用:

<head>
    <meta name="layout" content="main"/>
    <g:javascript library='jquery' plugin='jquery' />
</head>
<script type="text/javascript">
    function getNextIndex(){
        return 0;
    }
    function getReadyForNextRow(){
        var $span = $('#next-row');
        var $copy = $span.clone();
        $span.removeAttr('id');
        $copy.html('');
        $copy.insertAfter($span);
        var $Count = $('#count');
        $Count.val(parseInt($Count.val())+1);
    }
</script>
<div>
    <g:hiddenField name="Count" value="${list.size()}" id = "count"/>
    <div class="buttons">
        <g:actionSubmit class="add" value="Add Row"
                        onclick="${remoteFunction(controller: 'Controller', action: 'nextAction', update: 'next-row', params: '\'index=\'+getNextIndex()', onSuccess: 'getReadyForNextRow()')}"/>
    </div>
    <span id = "next-row"></span>
</div>

据我所知,它无法识别 javascript 函数 getNextIndex() 或 getReadyForNextRow()。我不知道为什么。我在尝试调试时注意到,远程函数没有调用控制器操作函数。但是,如果我更换

params: '\'index=\'+getNextIndex()'

params: '\'index=0\''

它可以调用控制器的动作函数。我不想将其用作解决方案,因为我希望(将来) getNextIndex() 返回不同的值而不仅仅是 0。

我愿意接受有关此代码为何不起作用的建议。

(请不要对命名约定发表评论,因为出于本示例的目的,我故意从我的实际代码中更改了名称。)

【问题讨论】:

  • 你不能将 javascript 值直接传递给 JS 世界中的 grails 函数 退后一步试试这个:` ` vs ` `希望有意义
  • @vahid 谢谢你的建议,但我不确定你的意思。
  • 您使用的是什么版本的 Grails? remoteFunction 标记已被弃用。我改用 jquery ajax。
  • @Joe 我正在使用 grails 2.2.4。我会尝试你的建议并尝试使用 jquery ajax。

标签: javascript grails


【解决方案1】:

根据 Joe 的建议,我改用了 jquery ajax。它现在按预期工作。这是更新的代码:

<head>
    <meta name="layout" content="main"/>
    <g:javascript library='jquery' plugin='jquery' />
</head>
<script type="text/javascript">
    function addRow(){
        $.ajax({
            url: "${g.createLink(controller: 'Controller', action:'nextAction')}" ,
            type: 'POST',
            data: {index: getNextIndex},
            update: "next-row",
            success:function(data,textStatus){
                jQuery('#next-row').html(data);
                getReadyForNextRow();
            }
        });
    }
    function getNextIndex(){
        return 0;
    }
    function getReadyForNextRow(){
        var $span = $('#next-row');
        var $copy = $span.clone();
        $span.removeAttr('id');
        $copy.html('');
        $copy.insertAfter($span);
        var $Count = $('#count');
        $Count.val(parseInt($Count.val())+1);
    }
</script>
<div>
    <g:hiddenField name="Count" value="${outsideLocations.size()}" id = "count"/>
    <div class="buttons">
        <g:actionSubmit class="add" value="Add Row" onclick="addRow(); return false;"/>
    </div>
    <span id = "next-row"></span>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-31
    • 2013-09-27
    • 2014-07-02
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多