通过Javascript / jQuery的阿贾克斯HEAD请求 [英] Ajax HEAD request via Javascript/jQuery
问题描述
我似乎有与制作 HEAD
请求和$ P $阵列中的pserving数据的完整性的一些问题。
I seem to be having some issues with making HEAD
requests, and preserving the integrity of data in an array.
鉴于这种片段:
var imageTemp = Array();
$('*')
.each(function(index){
if($(this).css('background-image') != 'none'){
imageTemp.push($(this).css('background-image').slice(5, -2));
}
});
我捕捉到一个特定网页上的所有背景图片的URL。现在,尝试通过 HEAD抓住每个图像的尺寸
为内容长度
的要求,我用这个片段:
I capture the URLs of all background-images on a given page. Now, trying to grab the size of each image via HEAD
requests for Content-Length
, I use this snippet:
var imageData = Array();
for(var i = 0; i < imageTemp.length; i++){
ajaxSizeRequest = $.ajax({
type: "HEAD",
async: true,
url: imageTemp[i],
success: function(message){
imageData.push([imageTemp[i], ajaxSizeRequest.getResponseHeader('Content-Length')]);
}
});
}
然而,当我倾倒为imageData code>通过
的console.log
,我每一个元素(这应该是包含数组URL和内容长度),最终为 [不确定,XXXX]
,其中 XXXX
是总规模最后要求内容长度
However, when I dump imageData
via console.log
, I each element (which should be an array containing the URL and the content-length) ends up as [undefined, XXXX]
where XXXX
is always the size of the last requested Content-Length
我很为难,虽然它似乎是一个计时/范围界定问题。我有一个排序的竞争条件存在的吗?
I'm stumped, though it appears to be a timing/scoping issue. Do I have a sort of race-condition occuring here?
推荐答案
问题是,单变量我
和 ajaxSizeRequest
被抓获的回调函数是回调函数的所有实例相同的变量。如果你调用一个函数和指数变量传递给它,并在同一时间,<击>范围请求变量本地函数本身我觉得击>使用做处理程序的响应参数,你应该结束了与由回调捕获独立变量。然后,它应引用每个数组元素,每个响应变量正确。
The problem is that the single variables i
and ajaxSizeRequest
being captured by the callback function are the same variables for all instances of the callback function. I think if you call a function and pass the index variable to it and, at the same time, scope the request variable locally to the function itself use the response parameter of the done handler, you should end up with independent variables captured by the callback. It should then reference each array element and each response variable correctly.
var imageData = Array();
for(var i = 0; i < imageTemp.length; i++){
updateImageData( i );
}
function updateImageData( i )
$.ajax({
type: "HEAD",
async: true,
url: imageTemp[i],
}).done(function(message,text,jqXHR){
imageData.push([imageTemp[i], jqXHR.getResponseHeader('Content-Length')]);
});
}
这篇关于通过Javascript / jQuery的阿贾克斯HEAD请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!