AJAX与Rails 3.2一起提交表单

这是我的表单,它工作正常,但现在我想要AJAX它。

 :put, :class => 'update_inv_form' do %>    

当我添加:remote => true属性时,表单通过AJAX成功提交(我可以看到它发生在服务器上,我可以在刷新页面时看到更改)。 我想正确更新视图以显示更改而不刷新页面。 这是我的更新操作:(请注意,我在这里不使用ActiveRecord模型。)

 def update variant = ShopifyAPI::Variant.find(params[:id]) variant.inventory_quantity = params[:inventory_quantity] variant.save redirect_to root_path end 

更新感谢您帮助我解决这个问题的答案结果解决方案正如他所说的那样,但是我遇到了一个小问题。 我想更新的视图存在于app/views/home/index.html.erb ,我正在处理这个问题:Variants #update。 (变种控制器,更新动作)

我把update.js.html放在我的视图所在的同一目录中: app/views/home和我的服务器抛出500错误:缺少模板。 事实certificate,我必须创建一个app/views/variants/目录并将update.js.html文件放在那里。 问题解决了。

您需要更改操作以响应JS格式:

 def update @variant = ShopifyAPI::Variant.find(params[:id]) @variant.inventory_quantity = params[:inventory_quantity] @variant.save respond_to do |format| format.html { redirect_to root_path } format.js end end 

然后,您可以使用JavaScript更新页面来创建update.js.erb文件。 假设您有一个_variant.html.erb partial,您可以将变量附加到这样的div(假设您使用的是jQuery):

 $('.variant-list').append('<%= escape_javascript(render(:partial => "variant", :object => @variant)) %>'); 

更新

这是一个如何使用update.js.erb' file (Note: I have not tried this code). Let's say you have the following code in your的例子update.js.erb' file (Note: I have not tried this code). Let's say you have the following code in your update.js.erb' file (Note: I have not tried this code). Let's say you have the following code in your index.html.erb`中update.js.erb' file (Note: I have not tried this code). Let's say you have the following code in your

 
  • Variant 1
  • Variant 2
  • Variant 3

你的updated.js.erb看起来像这样:

 $('.variants #<%= @variant.id %>').text('<%= @variant.title %>'); 

这样做是找到您刚刚在列表中更新的变体,并将变体标题更改为新标题。