如何处理单页应用程序中的非根 URL? [英] How to handle non-root URLs in a singlepage app?

查看:37
本文介绍了如何处理单页应用程序中的非根 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 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 的"路线.在这种情况下,如何加载页面并引导 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?

推荐答案

我终于找到了解决方案.

Finally I found the solution.

我把下面的代码放到了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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆