jQuery 使用 javascript 提交 Rails 远程表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8570824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:42:50  来源:igfitidea点击:

submit a rails remote form with javascript

jqueryruby-on-railsunobtrusive-javascript

提问by Matthew

In my rails app I have a remote form that looks something like this for example:

在我的 rails 应用程序中,我有一个远程表单,例如:

<%= form_tag some_path, :method => :get, :id => 'my-form', :remote => true do %>
  <%= text_field_tag :search, params[:search], :id => 'search-field' %>
  <%= submit_tag 'Go' %>
<% end %>

Now i would like to submit this form via javascript and trigger all rails remote form callbacks. So far i have tried a few things but nothing seems to be working.

现在我想通过javascript提交这个表单并触发所有rails远程表单回调。到目前为止,我已经尝试了一些东西,但似乎没有任何效果。

Things i have tried:

我尝试过的事情:

$('#my-form').trigger('onsubmit')

$.rails.callFormSubmitBindings( $('#search-form') )

but no luck so far. Any ideas?

但到目前为止还没有运气。有任何想法吗?

采纳答案by andrewpthorp

You can just use .submit();

你可以只使用 .submit();

$("#my-form").submit();

回答by mltsy

In Rails 5.1+, which replaces the old jquery-ujswith a non-jquery rails-ujs, the above answers no longer work, always submitting the form via an HTML HTTP request. This is how you trigger the new rails submit event handler:

在 Rails 5.1+ 中,jquery-ujs用非 jquery替换了旧的rails-ujs,上面的答案不再有效,总是通过 HTML HTTP 请求提交表单。这是触发新 rails submit 事件处理程序的方式:

var elem = document.getElementById('myform') // or $('#myform')[0] with jQuery
Rails.fire(elem, 'submit');

(Can't tell you how long it took me to figure that one out...) For some reason, the regular events don't bubble up properly to the delegated event handler attached by railsusing rails' new delegate function, when they are triggered by jQuery.

(不能告诉你我花了多长时间才弄明白……)出于某种原因,常规事件没有正确冒泡到使用 rails 的新委托函数由 rails 附加的委托事件处理程序,当他们由 jQuery 触发。

回答by Gopal S Rathore

This is simply in Rails way :

这只是在 Rails 方式:

 $("#myform").trigger('submit.rails');

回答by Mladen Ili?

How about using rails_ujsand simply do the following:

如何使用rails_ujs并简单地执行以下操作:

Rails.fire(form, 'submit');

(where formis a DOM Element)

(哪里form是 DOM 元素)

This feels like a proper Rails way to do it.

这感觉像是一个合适的 Rails 方式来做到这一点。

You can check out the source here – https://github.com/rails/rails/blob/master/actionview/app/assets/javascripts/rails-ujs/utils/event.coffee#L34

您可以在此处查看源代码 – https://github.com/rails/rails/blob/master/actionview/app/assets/javascripts/rails-ujs/utils/event.coffee#L34

回答by prasvin

How about passing json from controller and capturing it by your js.

如何从控制器传递 json 并由您的 js 捕获它。

Now, controller's action as

现在,控制器的动作为

respond_to do |format|
      if some condition
        format.json { render :json => {:success => true} }
        format.html{ redirect_to some_path, :notice => "successfully created" }
      else
        ...
      end
end

And capturing the json in js as

并将 js 中的 json 捕获为

$('#my-form').bind 'ajax:success', (event,data) ->
  if(data.success == true)
    ...

Not exactly what you are looking for but hope this turns out to be of any help.

不完全是您正在寻找的内容,但希望这对您有所帮助。

回答by mentatkgs

I'm updatting the answer to rails 6.

我正在更新 rails 6 的答案。

If you are having this issue in rails 6, it is likelly that you forgot to add the parameter "format: :js" to the form builder.

如果您在 rails 6 中遇到此问题,很可能您忘记将参数“format: :js”添加到表单构建器中。

<%= form_tag some_path, :method => :get, :id => 'my-form', :remote => true,
         :format => :js do %>
  <%= text_field_tag :search, params[:search], :id => 'search-field' %>
  <%= submit_tag 'Go' %>
<% end %>

You will also need to include a format.js in your controller.

您还需要在控制器中包含一个 format.js。

def update
    respond_to do |format|
      if @model.update(user_params)
        format.html { redirect_to @model, notice: 'Model was successfully updated.' }
        format.json { render :show, status: :ok, location: @model }
        format.js {
          logger.debug "this will run in the update was ok."
        }
      else
        format.html { render :edit }
        format.json { render json: @model.errors, status: :unprocessable_entity }
        format.js {
          logger.debug "this will run in the update was not ok."
        }
      end
    end
  end

Now, from the JavaScript, you can just call the submit to this form regularly.

现在,从 JavaScript 中,您可以定期调用此表单的提交。

this.form.submit()

回答by Jonas

I know this is an old topic but I have been struggling with this now for some time and finally found a solution.

我知道这是一个古老的话题,但我已经为此苦苦挣扎了一段时间,终于找到了解决方案。

I had a form with remote: truethat included a file_fieldand I wanted the form to submit automatically as soon as the user added the file. I tried onchange: form.submit();but that way the form was submitted as HTML.

我有一个remote: true包含 afile_field的表单,我希望表单在用户添加文件后立即自动提交。我试过了,onchange: form.submit();但是表单是作为 HTML 提交的。

My solution: clicking the (hidden) form submit button with JS:

我的解决方案:用JS点击(隐藏的)表单提交按钮:

onchange: $("#submit-button").click();

回答by James Hong

@mltsy answer works perfect for me. However, wanted to reiterate that this requires the use of rails-ujs. If you've upgraded from an older version like me, you might still be using the jquery dependent jquery_ujs. If you're getting ReferenceError: Can't find variable: Railsin your console, check your application.js and make sure you have rails-ujs or @mltsy's great answer won't work. I wanted to leave a comment instead of an answer, but Stack won't let me.

@mltsy 的答案对我来说很完美。但是,想重申一下,这需要使用 rails-ujs。如果您像我一样从旧版本升级,那么您可能仍在使用依赖于 jquery 的 jquery_ujs。如果您进入ReferenceError: Can't find variable: Rails控制台,请检查您的 application.js 并确保您有 rails-ujs 或 @mltsy 的好答案将不起作用。我想发表评论而不是回答,但 Stack 不让我做。