Rails 3 - 使用Ajax提交表单

时间:2012-08-20 04:07:14

标签: jquery ruby-on-rails ajax

我尝试使用ajax将表单提交给控制器并在我的视图中显示ajax响应。表格使用ajax提交,但我无法进入' ajax:成功'或者' ajax:错误'我的javascript中的方法。以下是它的代码段:

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

1 个答案:

答案 0 :(得分:1)

看起来您提供的ID不在选项中的正确subhash中。 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