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

    评论

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号