2016-06-08 43 views
1

我使用HTML 5 History API中的pushstate来更改我的单页应用程序中的URL。使用History.pushstate时,如何防止每次点击链接时网址变长?

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

我想改变的URL时,“家庭/索引/”每次要前置,使得它看起来像这样:

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 

等等,我想你明白了。我怎样才能防止这种情况发生?我想从history.pushstate的URL操作只是增加了URL链接到当前的URL使用绝对网址,而不是

回答

3

使用absoulte网址。随着 history.pushState(stateObj, nodeName, '/home/index/' + documentTitle); 可以直接从它的根部覆盖URL( - >“/”)

如果你的程序在运行子目录,你必须前缀这一点。含义:

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

尝试:

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

或开始用/的网址:

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

来自pushState的文档:

新的URL不必是绝对的;如果它是相对的,则相对于当前的URL解析为

相关问题