在 RoR 2.x 中使用 respond_to 通过 ajax 实现优雅降级
我正在阅读有关使用 ruby on Rails 进行 Web 开发的 AWDR 书籍,旧代码的问题之一是它没有使用 respond_to 来确保使用的视图是 javascript 视图。 现在,在一些更新的示例中,我看到人们稍后提到,在实现优雅降级时,使用 request.xhr? 判断用户是否启用了 javascript,如果没有,则重定向用户。
我想知道您是否可以使用 respond_to 来获得相同的行为,如果可以,这是否被认为是好的形式,为什么?
所以我想做的是这样的:
def function
respond_to do |format|
format.js do
basic_stuff
end
format.html do
basic_stuff
user_redirect
end
end
end
它似乎确实有点违反了 DRY 原则,而且我可能错过了有关用户和服务器如何交互的一些信息。 说实话,API 文档并没有让我完全清楚。
I was going through the AWDR book on web development with ruby on rails and one of the issues with the old code was it didn't use respond_to to make sure the view used would be the javascript view. Now in some updated examples I've seen people mention they later, when implementing graceful degradation, use request.xhr? to tell if the user has javascript enabled, and if not they redirect the user.
I was wondering if you could use respond_to to get the same behaviour and if so, if this is considered good form or not and why?
So what I'm thinking of doing is something like:
def function
respond_to do |format|
format.js do
basic_stuff
end
format.html do
basic_stuff
user_redirect
end
end
end
It does seem to sorta violate the DRY principle, and I'm probably missing something about how the user and the server are interacting here. To be honest the API documentation did not make it entirely clear to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那么您可以像这样重构:
request.xhr?
查看请求的X-Requested-With
标头(以查看它是否包含“XMLHttpRequest”)。respond_to
查看接受的 mime 类型。您可以使用其中任何一个来实现某种优雅的降级。
但是除非您的 ajax 调用设置该标头(Prototype 自动执行此操作),否则您将无法使用
xhr?
进行优雅的降级。此外,respond_to 提供了更大的灵活性,即发送 xml、json、js,无论它来自同一个块。
所以我在这里推荐
respond_to
。Well you can refactor like this:
request.xhr?
looks at the request‘sX-Requested-With
header (to see whether it contains "XMLHttpRequest").respond_to
looks at the mime types accepted.You can use either to implement some sort of graceful degredation.
BUT You won't be able to use
xhr?
for graceful degredation unless your ajax calls are setting that header (Prototype does this automatically).Moreover,
respond_to
gives more flexibility i.e. sending xml, json, js, whatever it might be from the same block.So I'd recommend
respond_to
here.