1

我能找到的最好的例子是选择了特定图像的谷歌图像页面的 URL。每个选定图像的 URL 都会发生变化。

在我的例子中,我有一个 Notebooks 模型和一个嵌套的 Notes 模型。在显示所有注释的视图中,当用户单击注释时,他/她将被带到注释显示视图。相反,我希望它们在同一视图中显示为部分内容,但我希望 URL 更改为包含有关所选笔记的信息。

我该怎么做呢?

4

1 回答 1

1

您可以replaceState()在 javascript 中执行此操作。当用户单击便笺时,您可以以任何方式打开便笺(例如使用 ajax 调用),然后当它打开时,您使用回调来触发replaceState()将用您想要的任何内容替换当前 url 的函数(我想你的笔记的网址)。

然后,当用户使用这个精确的 url 进入您的站点时,您可以解析 url 以显示他请求的注释(或让 Rails 默认行为将他重定向到您的注释显示视图)。

这是文档replaceState()https ://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_replaceState().C2.A0method

这是使用 jquery 来说明我的观点的相应视图的非工作示例:

= link_to "note", note_path(@note), id: 'x_link'

<script>
    $('#x_link').click(function(e) {
        e.preventDefault() //we do not let the event propagate
        href = $(this).attr('href') //we get the href attribute of our note
        $.get(href, function(data) {
            show_partial(data) // write some method to display you partial
            history.replaceState(null, null, href) //replace the current state
        })
    })
</script>
于 2013-10-23T15:10:15.133 回答