简体   繁体   English

使用History.pushstate时,如何防止每次单击链接时URL变长?

[英]When using History.pushstate how do I prevent the URL from getting longer each time I click on a link?

I'm using pushstate from the HTML 5 History API to change the URL in my single page application. 我正在使用HTML 5历史记录API中的pushstate更改单页应用程序中的URL。

history.pushState(stateObj, nodeName, 'home/index/' + documentTitle);

I want to prepend the "home/index/" each time when changing the URL so that it looks like this: 我想在每次更改URL时都在其前面加上“ home / index /”,使其看起来像这样:

mysite.com/home/index/documentTitle1

mysite.com/home/index/documentTitle2

mysite.com/home/index/documentTitle3

mysite.com/home/index/documentTitle4

But what happens is this instead: 但是发生的事情是这样的:

mysite.com/home/index/documentTitle1

mysite.com/home/index/home/index/documentTitle2

mysite.com/home/index/home/index/home/index/documentTitle3

mysite.com/home/index/home/index/home/index/home/index/documentTitle4

And so on I think you get the point. 依此类推,我想您明白了。 How can I prevent that from happening? 如何防止这种情况发生? I thought the URL manipulation from history.pushstate just adds the URL to the current URL 我认为从history.pushstate的URL操作只是将URL添加到当前URL

Use absoulte Urls. 使用Absoulte Urls。 With history.pushState(stateObj, nodeName, '/home/index/' + documentTitle); 使用history.pushState(stateObj, nodeName, '/home/index/' + documentTitle); you directly overwrite the url from its root (-> '/') 您可以直接从根目录(->'/')覆盖url

If your program runs on a subdirectory, you have to prefix this. 如果您的程序在子目录上运行,则必须为此添加前缀。 meaning: 含义:

var baseUrl = "/app1";
history.pushState(stateObj, nodeName, baseUrl + '/home/index/' + documentTitle);

Try using an absolute URL instead: 尝试改用绝对 URL:

history.pushState(stateObj, nodeName, 'http://example.com/home/index/' + documentTitle);

or starting the URL with a / : 或以/开头的URL:

history.pushState(stateObj, nodeName, '/home/index/' + documentTitle);

From the docs for pushState : pushState的文档中:

The new URL does not need to be absolute; 新的URL不必是绝对的。 if it's relative, it's resolved relative to the current URL 如果是相对的,则相对于当前URL进行解析

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM