0

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

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

结尾

4

1 回答 1

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

于 2012-08-20T05:13:16.080 回答