【问题标题】:Rails 3 - submit form using AjaxRails 3 - 使用 Ajax 提交表单
【发布时间】:2012-08-20 04:07:13
【问题描述】:

我正在尝试使用 ajax 将我的表单提交给控制器并在我的视图中显示 ajax 响应。表单使用 ajax 提交,但我无法在我的 javascript 中使用 'ajax:success' 或 'ajax:error' 方法。下面是它的代码sn-p:

form.html.erb

 <%= form_for @item, :html => { :class => 'form-horizontal' },:id => 'item_form', :remote => true do |f| %>
  <div class="control-group">
    <div class="controls">
      <%= f.text_field :item_title%>
    </div>
   </div>


   <div class="form-actions">
    <%= f.submit nil%>
   </div>
<% end %>

<%= javascript_tag do%>
jQuery(function($) {
alert ("load")
 $('#item_form')
 .bind('ajax:success', function(xhr, data, status) {alert ("success")})
 .bind('ajax:complete', function(xhr, status) {alert ("complete")})
 .bind('ajax:error', function(xhr, data, status) {alert ("error")})
});
<%end%>

控制器

def update
@item = Item.find(params[:id])
respond_to do |format|
  if @item.update_attributes(params[:item])
   format.html { 
      if request.xhr?
        puts "its an ajax req"
        render :json => {
            :location => url_for(:controller => 'items', :action => 'edit'),
        }

      end
   }
    format.json { head :no_content }
  else
    format.html { render action: "edit" }
    format.json { render json: @item.errors, status: :unprocessable_entity }
  end

end

结束

【问题讨论】:

  • 我还注意到,当我进行 ajax 提交时,我的表单提交了两次。我看到很少有帖子要求删除公共/资产,清除缓存然后重试。我也试过了,但没有帮助。

标签: jquery ruby-on-rails ajax


【解决方案1】:

您提供的 id 似乎不在选项中的正确子哈希中。 id 必须在 html 选项中,如下所示:

 <%= form_for @item, :html => { :class => 'form-horizontal', :id => 'item_form' }, :remote => true do |f| %>

如果表单上没有 html id,则您的事件不会被绑定。

文档参考: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for

【讨论】:

  • @user193545:我在一个带有项目脚手架的新应用程序中模仿了你的确切代码。修复 id 后,我成功收到了 success 和 complete 事件。我正在使用 ruby​​ 1.9.3 和 rails 3.2.8。以下是我遵循的步骤:1) rails new stackoverflow-test 2) rails g scaffold item item_title:string 3) rake db:migrate 4) rm public/index.html 5) > 如果还有什么我可以帮忙的,请告诉我。
猜你喜欢
  • 2012-11-27
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多