csdn产品小助手 2012-08-20 04:07 采纳率: 0%
浏览 25

Rails 3-使用Ajax提交表单

I'm trying to submit my form to controller using ajax and display ajax response in my view. The form submits using ajax but I'm unable to get to 'ajax:success' or 'ajax:error' methods in my javascript. Below is a code snippet for it:

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

controller

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

end

  • 写回答

1条回答 默认 最新

  • weixin_33735676 2012-08-20 05:13
    关注

    It looks like the id you are supplying is not in the correct subhash within the options. The id would have to be inside the html options like so:

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

    Without the html id on the form, your events are not being bound.

    Documentation reference: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料