在同一个标签上加载另一个页面,在地址栏上保留上一个网址
问题描述:
当用户在我的主页example.com
上时,他从我的页眉的下拉菜单中手动选择一个国家/地区,网址为example.com/usa
,我想要example.com/usa
在地址栏中没有example.com更改为example.com/usa
的情况下在相同的选项卡上打开。在同一个标签上加载另一个页面,在地址栏上保留上一个网址
这样做的网站的示例是okayafrica.com。当您从主页选择加拿大版本[该版本的网址为okayafrica.com/country/canada
]时,它将重新加载到同一个选项卡上并显示加拿大版,地址栏将为okayafrica.com
。
有没有一种方法,我可以用Javascript来实现这一点?
答
假设你使用jQuery,下面的代码应该足够了。
$("button").click(function(){// any event you can bind on which you want to load new page.
$("html").load("usa", function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("External content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
下面是完整的示例HTML代码以上说明。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("html").load("usa", function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("External content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
使用便接踵而来jQuery脚本:'$( “HTML”)负载(NEWURL)' – diavolic
听说过路由? –
@diavolic你可以帮助一个详细的代码答案。我对JavaScript一无所知。 :( – bobozar