在同一个标​​签上加载另一个页面,在地址栏上保留上一个网址

问题描述:

当用户在我的主页example.com上时,他从我的页眉的下拉菜单中手动选择一个国家/地区,网址为example.com/usa,我想要example.com/usa在地址栏中没有example.com更改为example.com/usa的情况下在相同的选项卡上打开。在同一个标​​签上加载另一个页面,在地址栏上保留上一个网址

这样做的网站的示例是okayafrica.com。当您从主页选择加拿大版本[该版本的网址为okayafrica.com/country/canada]时,它将重新加载到同一个选项卡上并显示加拿大版,地址栏将为okayafrica.com

有没有一种方法,我可以用Javascript来实现这一点?

+0

使用便接踵而来jQuery脚本:'$( “HTML”)负载(NEWURL)' – diavolic

+0

听说过路由? –

+0

@diavolic你可以帮助一个详细的代码答案。我对JavaScript一无所知。 :( – bobozar

假设你使用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> 
+0

你可以用html代码解释一下吗?现在,'button'是class或id吗? demo_test.xt是需要加载的页面的url吗? – bobozar

+0

已更新我的代码,$(“html”)。load(“url”,url是相对于当前页面的相对url。是url –

+0

当我在load()中插入'quick.html'时,它的工作原理就是它没有像在地址栏中加载quick.html时那样正确显示页面,但是当我在lo中输入'example.com' ad()函数,它会弹出错误0.它没有加载url。我将处理url而不是页面名称。有没有解决这个问题? :) – bobozar