【问题标题】::remote form with multiple submit buttons: 带有多个提交按钮的远程表单
【发布时间】:2010-11-17 17:17:42
【问题描述】:

我似乎无法获得带有多个提交控件的:remote 表单以在 Rails 3 下工作。以下代码:

<%= form_tag({:action => 'debug'}, {:remote => true}) do %>
  <%= submit_tag "Foo" %>
  <%= submit_tag "Bar" %>
<% end %>

生成一个带有两个按钮的表单,但生成的 AJAX POST 不包含commit 参数来说明按下了哪个按钮。如果我将:remote =&gt; true 排除在外,则正常的POST 确实包含commit 参数。

有什么办法可以使这个工作,还是只是一个错误?

【问题讨论】:

    标签: ajax forms ruby-on-rails-3


    【解决方案1】:

    玩了一会儿,我想我找到了解决办法。

    问题是rails.js 在包含被点击的submit 控件的form 元素上使用了serializeArray();但表单的序列化数据不包含该控件。但是,JQuery 或 Javascript 会跟踪调用链中的原始事件,这在技术上是适当控件上的“提交”事件。

    所以我编辑 rails.js 如下:

    callRemote: function (e) {   /* Note - new parameter e */
                var el      = this,
                    method  = el.attr('method') || el.attr('data-method') || 'GET',
                    url     = el.attr('action') || el.attr('href'),
                    dataType  = el.attr('data-type')  || 'script';
    
                if (url === undefined) {
                  throw "No URL specified for remote call (action or href must be present).";
                } else {
                    if (el.triggerAndReturn('ajax:before')) {
                        var data = el.is('form') ? el.serializeArray() : [];
                        /********************/
                        /* Note new if-test */
                        /********************/
                        if (e)
                        {
                            data.push({name: e.originalEvent.explicitOriginalTarget.name,
                            value: e.originalEvent.explicitOriginalTarget.value})
                        }
                        /* Function continues as before */
    

    ……再往下……

    $('form[data-remote]').live('submit', function (e) {
        $(this).callRemote(e);
        e.preventDefault();
    });
    

    这具有在触发 AJAX 之前添加单击按钮的名称-值对的效果。

    我对 Javascript 有点陌生,所以如果其中有任何严重错误,请告诉我!

    【讨论】:

    【解决方案2】:

    我尝试了您的解决方案,它适用于 Firefox,但随后该应用程序不再适用于 IE 和 Safari。现在我找到了另一种解决方案:简单地将提交按钮的值通过一个小的 javascript 放入隐藏的输入字段中。

    <input id="selected_button" type="hidden" name="commit" value=""/>
    <script>
      function identify_button( el ) {
        window.document.getElementById( 'selected_button' ).value = el.value;
      }
    </script>
    <input class="button"
           type="submit"
           name="commit"
           value="Save"
           onclick="identify_button( this )" );"
    />
    <input class="button"
           type="submit"
           name="commit"
           value="OK"
           onclick="identify_button( this )" );"
    />
    

    【讨论】:

      猜你喜欢
      • 2017-04-12
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 2016-09-17
      相关资源
      最近更新 更多