有没有办法使用simple_form for Rails提交ajax / json请求
使用标准的Rails form_for,我能够通过select和collection_select帮助程序传递ajax请求:
false}, "data-remote" => true, "data-url" => "/ajax/states", "data-type" => :json %>
我似乎无法弄清楚如何使用simple_form来做到这一点
弄清楚了。 你只需要添加这个:
:input_html => {"data-remote" => true, "data-url" => "/yoururl", "data-type" => :json}
我想发布一个相关的跟进,因为我很难搞清楚如何为此实现回调。 我发现这篇文章非常有帮助: http : //www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/
秘诀是要添加HTML5数据属性,例如data-complete
或(更好)绑定ajax:complete
或ajax:success
Rails为您的表单提供的ajax:success
回调(请参阅上面链接的文章中的4.远程JavaScript回调):
来自文章:
jQuery(function($) { // create a convenient toggleLoading function var toggleLoading = function() { $("#loading").toggle() }; $("#tool-form") .bind("ajax:loading", toggleLoading) .bind("ajax:complete", toggleLoading) .bind("ajax:success", function(event, data, status, xhr) { $("#response").html(data); }); });
CoffeeScript示例:
$("#new_post").on("ajax:success", (e, data, status, xhr)-> console.log data )
最好像这样写:
= simple_form_for sample_result, url: reject_sample_result_path(sample_result), method: :post, remote: true, input_html: {multipart: true} do |f|
当您明确声明data-url
它仍将首先进行默认路由计算,在我的情况下失败,因为默认路由不存在(并且不应该存在 – 因为我正在覆盖url)。 当你声明url
它只会取代给定的url。
现在看来这样做的有效方法是:
:remote => true, :html => { :data => { :url => '/yoururl', :type => :json } }
使用ruby 1.9 hash语法看起来可能会更好一些:
remote: true, html: { data: { url: '/yoururl', type: :json } }
https://github.com/plataformatec/simple_form/wiki/HTML5-Attributes
我找到的最简单的方法,以及更完整的例子,是:
在你看来:
<%= simple_form_for :my_object, url: my_objects_path(format: :json), remote: true do |f| %> <%= f.error_notification %> <%= f.input :an_attribute %> <%= f.submit %> <% end %>
在你的控制器中:
def create @my_object = MyObject.new(my_object_params) if @my_object.save respond_to do |format| format.html { redirect_to @my_object, notice: "Saved" } format.json { render json: @my_object, location: my_object_url(@object), status: :created } end else respond_to do |format| format.html { render :edit } format.json {render json: @my_object, status: :unprocessable_entity } end end end
在Rails 5中,安装Jbuilder的控制器更容易创建简单的json哈希,但这也应该在那里工作。
- “respond_to do | format |”抛出UnknownFormat错误
- Rails表单:使用AJAX基于其他collection_select值更新collection_select选项
- 在ajax请求中的rails中的Gettin 500内部服务器错误
- $ .AJAX用于在rails中创建多个记录
- 如何将remote_form_for的:update =>’div_id’选项从Rails 2升级到Rails 3?
- 使用Ruby On Rails在AJAX中获得星级评分
- will_paginate页面链接问题
- 保护AJAX API以防止其他网站利用它
- 就像Ruby on Rails中的按钮Ajax一样