如何在单页应用程序中处理非根 URL? [英] How to handle non-root URLs in a singlepage app?
问题描述
我尝试使用 Rails 3.2 和 Backbone.js 制作带有 pushState 选项的单页应用程序,但遇到了一些我不理解的问题.
I try to make a single page app with Rails 3.2 and Backbone.js with pushState option but faced with something that I do not understand.
如果我加载应用程序的根 URL (/),一切正常:Rails 返回一个带有 JS 的 HTML 布局,它引导 Backbone,它为 JSON 实体生成一些 XHR 并呈现内容.
If I load the root URL of the app (/), everything goes right: Rails return an HTML-layout with JS which bootstraps Backbone which makes some XHRs for JSON-entities and renders the content.
但是,如果我从 非根 URL 开始使用应用程序(例如,通过在浏览器的地址栏中手动输入),那么 Rails 将尝试使用来自 routes.rb 的路由规则来处理此请求 -这是错误的,因为它是骨干"路线.在这种情况下,如何加载页面和引导 Backbone 以处理此 URL?
But if I start using app from non-root URL (e.g. by manually typing it in the browser's address bar) then Rails will try to handle this request using theirs routing rules from routes.rb - that's wrong, cause it's a "Backbone's" route. How do I load the page and bootstrap Backbone for handling this URL in that case?
推荐答案
终于找到了解决方案.
我将以下代码放入我的 routes.rb 中
I put the following code into my routes.rb
class XHRConstraint
def matches?(request)
!request.xhr? && !(request.url =~ /.json$/ && ::Rails.env == 'development')
end
end
match '(*url)' => 'home#index', :constraints => XHRConstraint.new
使用这个匹配器,所有非 XHR 请求都被路由到返回 HTML 页面的 HomeController.XHR 请求将由返回 JSON 响应的其他控制器处理.我还留下了以.json"结尾的请求在开发环境中有效以进行调试.
With this matcher all non-XHR requests are routed to HomeController which returns an HTML page. And XHR requests will be handled by other controllers which return JSON responses. Also I left requests ending with ".json" as valid in development environment for debugging.
这篇关于如何在单页应用程序中处理非根 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!