
[英]How to reference a variable in one file, and be able to use across multiple files?
[英]How to use the same HTML page across multiple URLs except for the value of one variable depending upon URL queried?
我有一个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.html
和page2.html
只是设置一个变量的值,我认为这很多余。
我希望能够根据查询的URL设置此变量的值。 我怎样才能做到这一点?
PS:我正在使用快递服务器托管内容。
您可以将所有json数据存储到.json
文件中,然后查找window.location对象的hash属性以查询良好的对象:对于此示例,假设您有file1.json,file2.json等。
var hash = window.location.hash;
var jsonPage;
if ( hash.length ) {
jsonPage = hash.split('#')[1]
}
else {
jsonPage = 1;
}
现在,您可以根据html文件名(即your_url/page.html#2
之后的值调用json页面:
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
事件,该事件不会刷新页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.