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| %>

フォームにhtmlIDがないと、イベントはバインドされません。

ドキュメントリファレンス: http ://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for

于 2012-08-20T05:13:16.080 に答える