代码之家  ›  专栏  ›  技术社区  ›  Chowlett

:带有多个提交按钮的远程窗体

  •  3
  • Chowlett  · 技术社区  · 14 年前

    我好像找不到 :remote 具有多个提交控件的窗体在Rails3下工作。以下代码:

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

    生成带有两个按钮的表单,但生成的AJAX帖子不包含 commit 参数来说明哪个被按下。如果我离开 :remote => true 不,正常的帖子包含 犯罪 参数。

    有什么办法能让它起作用,还是只是一个bug?

    2 回复  |  直到 13 年前
        1
  •  1
  •   Chowlett    14 年前

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

    问题是 rails.js 使用 serializeArray() form 包含已单击的 submit 控件;但窗体的序列化数据不包含该控件。但是,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
  •  1
  •   Martin    13 年前

    我尝试了你的解决方案,它在Firefox上运行,但是这个应用程序在IE和Safari上不再运行了。现在我找到了另一个解决方案:通过一个小的javascript将submit按钮的值放入一个隐藏的输入字段。

    <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 )" );"
    />