Javascript 使用History.pushstate时,如何防止每次单击链接时URL变长?
我正在使用HTML5历史API中的pushstate来更改单页应用程序中的URLJavascript 使用History.pushstate时,如何防止每次单击链接时URL变长?,javascript,Javascript,我正在使用HTML5历史API中的pushstate来更改单页应用程序中的URL history.pushState(stateObj, nodeName, 'home/index/' + documentTitle); 每次更改URL时,我都希望在“home/index/”前面加上前缀,使其看起来像这样: mysite.com/home/index/documentTitle1 mysite.com/home/index/documentTitle2 mysite.com/home/in
history.pushState(stateObj, nodeName, 'home/index/' + documentTitle);
每次更改URL时,我都希望在“home/index/”前面加上前缀,使其看起来像这样:
mysite.com/home/index/documentTitle1
mysite.com/home/index/documentTitle2
mysite.com/home/index/documentTitle3
mysite.com/home/index/documentTitle4
但实际情况是:
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
等等,我想你明白了。我怎样才能防止这种情况发生?我认为历史记录中的URL操作。pushstate
只是将URL添加到当前URL尝试使用绝对URL:
history.pushState(stateObj, nodeName, 'http://example.com/home/index/' + documentTitle);
或以/
开头的URL:
history.pushState(stateObj, nodeName, '/home/index/' + documentTitle);
从pushState
的文档中:
新的URL不需要是绝对的;如果是相对的,则相对于当前URL解析
使用绝对URL。具有
history.pushState(stateObj,节点名,'/home/index/'+documentTitle)代码>
您可以直接从其根(->'/')覆盖url
如果您的程序在子目录上运行,则必须为其添加前缀。意思是:
var baseUrl = "/app1";
history.pushState(stateObj, nodeName, baseUrl + '/home/index/' + documentTitle);