2013-02-15 43 views
0

Codeschool's rails course给了下面的代码用json(format.json)做ajax。为什么代码与使用不显眼的javascript(format.js)做Ajax的方式如此不同?在Rails中用json做ajax的习惯性方法?

具体而言,我注意到下面的代码完全避免了UJS,并且没有在form_for中使用remote: true。这与在form_for中使用remote: true的不显眼javascript方法完全不同。

为什么remote: true不是针对json的json提议?我本以为ajax和json会使用remote: true,并且有一些方法可以让客户端javascript将success函数注册到UJS中,以便服务器的响应被UJS解释为json数据并传递给success函数而不是UJS尝试执行就像在不显眼的javascript方法中所做的一样。

有没有更好的方式做json比json比下面更好?

/views/zombies/show.html.erb 

<div id="custom_phase2"> 
    <%= form_for @zombie, url: custom_decomp_zombie_path(@zombie) do |f| %> 
    <%= f.text_field :decomp %> 
    <%= f.submit "Set" %> 
    <% end %> 
</div> 


/app/assets/javascripts/zombies.js.coffee 

$(document).ready -> 
    $('div#custom_phase2 form').submit (event) -> 
    event.preventDefault() 

    url = $(this).attr('action') 
    custom_decomp = $('div#custom_phase2 #zombie_decomp').val() 

    $.ajax 
     type: 'put' 
     url: url 
     data: { zombie: { decomp: custom_decomp } } 
     dataType: 'json' 
     success: (json) -> 
     $('#decomp').text(json.decomp).effect('highlight') 
     $('div#custom_phase2').fadeOut() if json.decomp == "Dead (again)" 
+0

考虑使用AngularJS,EmberJS或其他用得好的框架如上市这里以实例阐述:http://addyosmani.github.com/todomvc/它的优良学习如何在JQuery中做,但是要利用已经写好的东西。 – 2013-02-18 16:24:45

回答

0

可以使用remote_form_for帮手:

/views/zombies/show.html.erb 

<div id="custom_phase2"> 
    <%= remote_form_for @zombie, url: custom_decomp_zombie_path(@zombie), :update => {:success => "form", :failure => "errors"} do |f| %> 
    <%= f.text_field :decomp %> 
    <%= f.submit "Set" %> 
    <% end %> 
</div> 

这里的“形式”,这将是对sucess更新和“错误”的元素的ID的元素的ID即会如果有错误,则更新。

参考文献:herehere

相关问题