从Ajax调用中传递一个变量的函数 [英] Pass a variable to a function from inside an ajax call
问题描述
我试图用这个循环读取某些URL阅读他们的修改时间:
I tried to use this loop to read some urls to read their modified time:
var arr = [];
//... fill arr with push
for (var e in arr) {
nodename=arr[e].hostname;
node_json="/nodes/"+nodename;
html +='<a href="'+node_json+'" target="_blank" id="host_'+nodename+'">data</a>';
xhr = $.ajax({
url: node_json,
success: (function(nn) {
$('#host_'+nn).append("last modified: " + xhr.getResponseHeader("Last-Modified"));
})(nodename)
});
这已经运作了一下我我注释掉成功
行:我得到调用的所有节点的文件,并在Firebug的,我可以看到在不同的修改时间呼叫的头
This already works a bit i I comment out the success
line: I get calls to all node-files, and in Firebug, I can see the different modified times in the header of the calls.
起初,我有一个封闭,(请参阅<一href="http://stackoverflow.com/questions/6487366/how-to-generate-event-handlers-with-loop-in-javascript">How生成具有循环事件处理程序的Javascript?)我只得到了修改与所有结果的最后一行。这就是为什么我试图把动作在一个单独的函数。
At first I had a closure, (see How to generate event handlers with loop in Javascript?) And I only got the last line modified with all results. that's why I try to put the action in a separate function.
但是,这给了:
的ReferenceError:XHR没有定义
$('#主机_'+ NN).append(最后修改:+ xhr.getResponseHeader(上次修改)......
ReferenceError: xhr is not defined
$('#host_'+nn).append("last modified: " + xhr.getResponseHeader("Last-Modified")...
我如何获得 XHR
进入该功能?
How do I get xhr
into that function?
我aslo尝试:
...
xhr[e] = $.ajax({
url: node_json,
success: add_result_to_info(nodename, e)
});
}
}
// outside loop
function add_result_to_info(nn, e) {
$('#host_'+nn).append("last modified: " + xhr[e].getResponseHeader("Last-Modified"));
}
源的AJAX调用的:<一href="http://stackoverflow.com/questions/25062132/get-the-modified-timestamp-of-a-file-with-javascript/25064125?noredirect=1#25064125">Get用JavaScript文件的修改时间戳记 的
推荐答案
如果改编
确实是一个数组,只需使用 .forEach
甚至更好 .MAP
(对旧的浏览器垫片)封装每次迭代的范围,而不需要额外的关闭:
If arr
is truly an array, just use .forEach
or even better .map
(with a shim on older browsers) to encapsulate each iteration's scope without the need for additional closures:
var xhrs = arr.map(function(e) {
var nodename = e.hostname;
var node_json = "/nodes/" + nodename;
html +='<a href="'+node_json+'" target="_blank" id="host_'+nodename+'">data</a>';
return $.ajax({
url: node_json
}).done(function(data, status, xhr) {
$('#host_'+nodename).append("last modified: " + xhr.getResponseHeader("Last-Modified"));
});
});
之所以使用 VAR xhrs = arr.map()
而不是 .forEach
是那么(免费)获得调用另一个回调一次AJAX请求已完成的能力:
The reason to use var xhrs = arr.map()
instead of .forEach
is that you then (for free) get the ability to call yet another callback once every AJAX request has completed:
$.when.apply($, xhrs).then(function() {
// woot! They all finished
...
});
这篇关于从Ajax调用中传递一个变量的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!