简体   繁体   English

您应该从Rails服务器返回javascript(.js.erb)还是在Ajax调用后更新页面时使用本机JS回调机制

[英]Should you return javascript (.js.erb) from the Rails server OR use the native JS callback mechanism when updating the page after a Ajax call

I am doing an ajax call (using JQuery) and the Rails controller needs to return a partial so I can update the page after the ajax call. 我正在执行ajax调用(使用JQuery),并且Rails控制器需要返回部分信息,以便在ajax调用之后可以更新页面。 It seems to me there are 2 ways of doing this. 在我看来,有两种方法可以做到这一点。 In the controller, you filter for ajax calls (request.xhr?) and return: 在控制器中,过滤ajax调用(request.xhr?)并返回:

  1. a .js.erb which gets executed on the client side as part of the Ajax call itself (dataType : script). 一个.js.erb,它作为Ajax调用本身的一部分在客户端执行(dataType:脚本)。 This .js.erb file manipulates the DOM and injects the partials' html, something like this: 这个.js.erb文件操作DOM并注入部分的html,如下所示:

    $('#content').html("<%= escape_JavaScript(render :partial => 'success') %>"); $('#content')。html(“ <​​%= escape_JavaScript(render:partial =>'success')%>”));

  2. a partial ((dataType : html). You have a success callback method on the ajax call that then performs the inject, something like this: 部分((dataType:html)。在ajax调用上有一个成功的回调方法,然后执行注入,如下所示:

    $.post( url, send_data, function( data ) { $( "#result" ).empty().append( data ); } $ .post(url,send_data,function(data){$(“ #result”).empty()。append(data);}

These 2 solutions both work perfectly, I just don't know which one is considered better coding practice and easier to maintain down the line. 这两种解决方案都可以完美地工作,我只是不知道哪种解决方案被认为是更好的编码实践,并且更容易维护。

The second option is ideal. 第二种选择是理想的。 The Server should never be concerned with the Client. 服务器永远不要与客户端有关。

I would say the second option too, because it makes sense when talking from a RESTful perspective. 我也要说第二种选择,因为从RESTful角度讲这很有意义。

I talk about this in a blog entry "Rails, REST and JS - We're doing it wrong" 我在博客文章“ Rails,REST和JS-我们做错了”中谈到了这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM