如何跨多个URL使用相同的HTML页面,除了一个变量的值取决于所查询的URL

How to use the same HTML page across multiple URLs except for the value of one variable depending upon URL queried?

本文关键字:URL 一个 查询 取决于 变量 何跨多 页面 HTML      更新时间:2023-09-26

我有一个如下的HTML页面

<body ng-controller="DashboardDisplay" onload="submit()">
    <div class="container-fluid" >
        {{scope.arr}}
    </div>
</body>
<script>
var myApp = angular.module('myApp',[]);
myApp.controller('DashboardDisplay', ['$scope','$http',function($scope,$http) {
    $scope.submit = function(){
        var jsonOb = {"A":"B"};
        $http.post(URL,jsonOb).
        success(function(response) {
            console.log('got it' + response);
            $scope.arr=response;
        })
    }
    }]);

目前我硬编码变量jsonOb的值。对于不同的页面,除了jsonOb的值外,整个HTML保持不变。例如,如果我查询www.xyz.com/page1.html的值是jsonOb={"A":"B"},但www.xyz.com/page2.html的值是jsonOb={"1":"2"}。除此之外,这两个HTML页面是相同的,即我使用两个单独的HTML页面,即page1.htmlpage2.html只是设置一个变量的值,我认为这是相当多余的。

我希望能够根据正在查询的URL设置该变量的值。我该怎么做呢?

PS:我正在使用一个快速服务器来托管内容。

您可以将所有json数据存储到.json文件中,然后查找窗口的哈希属性。Location对象来查询好的Location:对于本例,假设您有file1。json、file2。json等…

var hash = window.location.hash;
var jsonPage;
if ( hash.length ) {
     jsonPage = hash.split('#')[1]
     }
else {
     jsonPage = 1;
     }

现在您可以根据html文件名后的值调用json页面,即your_url/page.html#2:

var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest();
else if (window.ActiveXObject) xhr = new window.ActiveXObject("Msxml2.XMLHTTP");
if(!xhr){
    checkOldBro(true); 
    return;
    }
xhr.onreadystatechange = function(){
    if (xhr.readyState == 4 && xhr.status == 200){
        var jsonOb = JSON.parse(xhr.responseText);
        $scope.submit = function(){...your function}
        }
    };
xhr.open("GET", "file"+jsonPage+".json", true);
xhr.send();
})(this);

请注意,您还可以检查hashchange事件,该事件不会刷新您的页面。