[英]How to refresh a page whenever my js data file changes
So I've got this local file named 'data.js' containing various data. 所以我有这个名为'data.js'的本地文件包含各种数据。
var json={ 'city': 'madrid', 'zip':'21212', 'street':'bergstrasse', 'house':'15', }; for(key in json) { if(json.hasOwnProperty(key)) $('input[name='+key+']').val(json[key]); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <form action="options.php" method="post" > <input type="text" name="city" placeholder="stadt" > <br> <input type="text" name="zip" placeholder="zip" > <br> <input type="text" name="street" placeholder="straße" > <br> <input type="text" name="house" placeholder="hausnummer" > <br> <input type="submit" value="speichern" name="saves"></input> </form> <script src="data.js"></script>
I want to refresh my page only when some data in the js file changes. 我只想在js文件中的某些数据发生变化时刷新页面。 Appreciate your help if you can explain me with bit of code.
如果您能用一些代码解释我,请感谢您的帮助。 I searched all over internet, I couldnt find appropriate answer.
我在互联网上搜索,我找不到合适的答案。
Let's break this down. 让我们打破这个。 You want to:
你想要:
As mentioned in the comments, there are ways to do all of the above in Javascript. 正如评论中所提到的,有很多方法可以在Javascript中完成上述所有操作。
First let's address checking something periodically: you can either use a recursive setTimeout
loop, or setInterval
: 首先让我们定期检查一些东西:你可以使用递归的
setTimeout
循环,也可以使用setInterval
:
function waitOneSecond = function() {
setTimeout(function() {
check(); // will get to this in a second
waitOneSecond();
}, 1000); // 1000 = one second
});
function checkEverySecond() {
setInterval(function() {
check();
}, 1000); // 1000 = one second
Next, we need a way to check whether the file changed. 接下来,我们需要一种方法来检查文件是否发生了变化。 The actual "did it change part" is up to you (you might want to consider using a function like Underscore or Lodash's
_.isEqual
for it), but to do that you'll need to get the latest version of the JSON file. 实际的“它改变了部分”取决于你(你可能想考虑使用像Underscore或Lodash的
_.isEqual
这样的函数),但要做到这一点,你需要获得最新版本的JSON文件。 Luckily jQuery has a method for doing exactly that: getJSON
: 幸运的是jQuery有一个方法可以做到这一点:
getJSON
:
function check() {
$.getJson('http://yourserver.com/data.js').done(function(json) {
if (didChange(json)) {// use _.isEqual to write your didChange
takeAction();
}
});
}
As you can see this last example also covers taking action, but again I'll leave the definition of the takeAction
function to you. 正如您所看到的,最后一个示例也涵盖了采取行动,但我将再次将
takeAction
函数的定义takeAction
您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.