2012-04-21 103 views
6

随着标准的Rails的form_for,我能够通过选择,虽然和collection_select助手Ajax请求这样:有没有办法与simple_form提交AJAX/JSON请求为Rails

<%= address.collection_select :country, @countries, :id, :name, {:include_blank => false}, "data-remote" => true, "data-url" => "/ajax/states", "data-type" => :json %> 

我似乎无法要弄清楚如何做到这一点simple_form

回答

14

想通了。你只需要添加此:

:input_html => {"data-remote" => true, "data-url" => "/yoururl", "data-type" => :json} 
+1

谢谢。一个后续问题 - 你是如何设置你的JavaScript回调? – Blake 2013-04-26 15:05:49

+1

我很困惑如何实现这一点。整行代码的外观如何? f.input:my_field:collection => ???? – SteveO7 2014-04-24 15:27:05

+0

对于一些新的浏览器(2015 :)),您需要添加'format :: json'以使表单正常工作,如: '<%= simple_form_for(@object,html:{class:'your_class' ,id:“#new”}},url:your_resource_path(@object,format :: json),remote:true,authenticity_token:true,data:{type:'json'})do | f |%> #Code <%end%>' – Aleks 2015-05-11 13:50:23

2

看来有效的方式,现在要做到这一点是:

:remote => true, :html => { :data => { :url => '/yoururl', :type => :json } } 

这可能看起来有点更好地与Ruby 1.9的哈希语法为:

remote: true, html: { data: { url: '/yoururl', type: :json } } 

https://github.com/plataformatec/simple_form/wiki/HTML5-Attributes

+0

它应该是':input_html =>'而不是':html =>' – Matt 2013-03-07 21:53:45

6

我想发布一个相关的跟进,因为我有一些困难计算了解如何实现此回调。我发现这篇文章是非常有用的:http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/

秘密是要么添加一个HTML5数据属性,例如, data-complete或(更好)通过绑定Rails的提供给您的表格(见4.远程JavaScript回调在文章上面链接)的ajax:completeajax:success回调:

从文章:

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 
) 
6

最好是把它写这样的:

= 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时,它只会取而代之。

0

要做到这一点,我发现,并为更全面例如最简单的方法是:

在你看来:

<%= 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哈希,但这也应该在那里工作。

相关问题