是否可以仅使用JavaScript来获取文件的修改后的时间戳?
我使用JSON文件通过javascript填充页面,我想显示该JSON文件的时间戳。
如果您通过真正的ajax(即通过XMLHttpRequest
)检索文件,则可以这样做,前提是您将服务器配置为Last-Modified
在发送数据时发送标头。
这里的基本要点是,当您使用时XMLHttpRequest
,您可以访问响应头。因此,如果服务器发回邮件Last-Modified
,则可以使用它:
var xhr = $.ajax({
url: "data.json",
success: function(response) {
display("Data is " + response.data + ", last modified: " + xhr.getResponseHeader("Last-Modified"));
}
});
刚刚在Chrome,Firefox,IE8和IE11上尝试过。运行良好(即使数据来自缓存)。
您在下面说过,您需要循环执行此操作,但是您始终看到变量的最后一个值。这说明我已经完成了以下操作:
// **WRONG**
var list = /*...some list of URLs...*/;
var index;
for (index = 0; index < list.length; ++index) {
var xhr = $.ajax({
url: list[index],
success: function(response) {
display("Data is " + response.data + ", last modified: " + xhr.getResponseHeader("Last-Modified"));
}
});
}
那里的问题是所有success
回调都对该变量有持久的引用xhr
,而其中只有一个。因此,所有回调都将看到分配给的最后一个值xhr
。
这是经典的关闭问题。这是一种解决方案:
var list = /*...some list of URLs...*/;
list.forEach(function(url) {
var xhr = $.ajax({
url: url,
success: function(response) {
display("Data for " + url + " is " + response.data + ", last modified: " + xhr.getResponseHeader("Last-Modified"));
}
});
});
由于forEach
回调的每个迭代都有其自己的xhr
变量,因此不会产生串扰。(您需要forEach
在旧版浏览器上进行填充。)
您在下面说:
我已经考虑过关闭问题,这就是为什么我
xhr[e]
在循环中使用数组的原因e
……但是您的示例确实有帮助……
并链接到此代码的要点:
//loop over e....
nodename=arr[e];
node_json=path_to_node_json+nodename;
html +='<a href="'+node_json+'" target="_blank" id="host_'+nodename+'">data</a></td>'
+'</tr>';
xhr[e] = $.ajax({
url: node_json,
success: function(response) {
$('#host_'+nodename).append("last modified: " + xhr[e].getResponseHeader("Last-Modified"));
}
});
仍然存在经典错误:success
函数关闭变量 e
,而不是success
创建函数时的值,因此在success
函数运行时,e
将在循环中为其分配最后一个值。
forEach
我之前给出的示例非常适合:
// (I assume `node_json`, `html`, and `path_to_node_json` are all declared
// here, outside the function.)
arr.forEach(function(nodename) {
var xhr; // <=== Local variable in this specific call to the iteration
// function, value isn't changed by subsequent iterations
node_json=path_to_node_json+nodename;
html +='<a href="'+node_json+'" target="_blank" id="host_'+nodename+'">data</a></td>'
+'</tr>';
xhr = $.ajax({
url: node_json,
success: function(response) {
// Note: You haven't used it here, but just to emphasize: If
// you used `node_json` here, it would have its value as of
// the *end* of the loop, because it's not local to this
// function. But `xhr` is local, and so it isn't changed on
// subsequent iterations.
$('#host_'+nodename).append("last modified: " + xhr.getResponseHeader("Last-Modified"));
}
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句