Rails RJS 有什么明显的危害么?

kalasoo · 2014年04月13日 · 最后由 simlegate 回复于 2014年04月27日 · 3081 次阅读

第一次用到 rjs 觉得很方便好用,但是又看到了Do not use RJS-like techniques,心里面就比较困惑了。

我不知道到底有没有什么大的问题,诚心求教。


补充:RJS leaking vulnerability in multiple Rails applications

先这样做,以后再思考。

RJS 简单易于理解,但我认为可维护性与安全性有一些问题。不过 DHH 非常推荐,BaseCamp 80% 的 JS 用的这个。

ps: 据我在深圳的 Ruby 圈子了解,70% 左右的 Rails 开发人员使用 Cient Javscript, 20% 使用 RJS, 10% 使用前端 MVC, 如 BackBone.js 等

本质上,其实都是执行 JS 代码。

如果用了 RJS,虽然说,能够很方便地直接根据逻辑然后执行相关的 JS 代码, 但是这样会把原本应该在同个地方的代码拆分出来了。 你要看什么逻辑,还必须得到模板里去看, 这个跟把代码逻辑直接全部交由前端 JS 代码还是有区别的, 逻辑不会太多还好,逻辑要是多了,那代码阅读起来就比较困难了,更别说维护代码了。

谢谢回复,我基本上也都是用 RJS 实现的,结果刚看到这几个 posts,开始思考了。

#2 楼 @hz_qiuyuanxin 你的意思是?就是如果用 rjs 的话,就会把一起的前端 html 要因为 rjs 而拆分成好几个小的 parts

讨论好长。。。 反正我经常用,好像不要用在 get 的时候返回 RJS 就好了?

说实话不太喜欢 rjs. 推崇 前后端完全分离。

好像升级到 4.1,get 返回 RJS 也是安全的了:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
end

For Rails 4.1: https://github.com/rails/rails/pull/13345

Since we don't know the response format until rendering, it's simplest to use an after_action to verify that we aren't serving JS to a non-XHR GET request.

This piggybacks on the same protect_from_forgery declarations that apps already use, so they'll transparently get protection without changing anything.

Apps that intentionally expose JavaScript responses (like third-party widgets, per-customer API embeds, etc) will need to exclude those actions using existing protect_from_forgery API.

Thanks everyone for the (long) discussion and thanks to Egor for the initial report - months ago now! - and this reminder.

Thank you all guys!

#6 楼 @zgm 嗯,rjs 更多的是为了简介快速完成一些小的 ajax 实现。但每一个部分基本上都要单独写,确实 reuse 起来比较难

我想请问各位,RJS 怎么支持回调? 比如我在界面上点击某个元素,后台返回的 Js 怎样吧这个元素删除?

#12 楼 @simlegate 我的理解是:

<% link_to '求戳我', lovely_path(:format => :js), :remote => true, :method => :post, :id => 'to-be-deleted' %>

然后可爱的lovely_path所对应的 controller 就会根据这个 request 来 ajax 返回 js。 在 view 里面应该是:

$('#to-be-deleted').remove();

然后这个 element 就会被删除了。

假如说(稍微复杂一点,你是想改变那个 link 里面的字),那对应的 view 里面就会是:

$('#to-be-deleted').text('<%=j @message_you_want_to_update %>');

#13 楼 @kalasoo 一个比较稍微复杂点场景: 当我有多个链接 (link_to),点击,后台操作成功后删除这个连接,在不传参数 (link 的 id) 的情况下,怎么做?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号