如何处理非根的URL在singlepage应用程序? [英] 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的返回一个HTML布局JS其中白手起家骨干这使得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.
但是,如果我开始使用应用程式的非根网址的(例如,通过在浏览器的地址栏手动输入),那么Rails会尝试使用从routes.rb中他们的路由规则来处理此请求 - 这是错误的,因为它是一个骨干的路子。我如何加载页面和引导骨干,在这种情况下处理这个网址?
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?
推荐答案
我终于找到了解决办法。
Finally I found the solution.
我把下面的code到我的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请求路由到HomeController中返回一个HTML页面。和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在singlepage应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!