在同一选项卡上加载另一个页面,维护地址栏上的上一个URL

时间:2017-08-24 09:40:48

标签: javascript jquery

如果用户位于我的主页example.com,并且我从标题的下拉菜单中手动选择了一个国家/地区,则网址为example.com/usa,我希望example.com/usa在没有example.com的相同标签在地址栏中更改为example.com/usa

执行此操作的网站示例为okayafrica.com。当您从主页选择加拿大版本[版本的网址为okayafrica.com/country/canada]时,它将在同一标签上重新加载并显示加拿大版本,地址栏将为okayafrica.com

有没有办法可以通过Javascript实现这一目标?

1 个答案:

答案 0 :(得分:0)

假设您使用的是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>