简体   繁体   English

Ajax HEAD通过Javascript / jQuery请求

[英]Ajax HEAD request via Javascript/jQuery

I seem to be having some issues with making HEAD requests, and preserving the integrity of data in an array. 我似乎在制作HEAD请求时遇到了一些问题,并保留了数组中数据的完整性。

Given this snippet: 鉴于此片段:

var imageTemp = Array();

$('*')
    .each(function(index){
        if($(this).css('background-image') != 'none'){
            imageTemp.push($(this).css('background-image').slice(5, -2));
        }
    });

I capture the URLs of all background-images on a given page. 我捕获给定页面上所有背景图像的URL。 Now, trying to grab the size of each image via HEAD requests for Content-Length , I use this snippet: 现在,尝试通过HEAD请求Content-Length来获取每个图像的大小,我使用此代码段:

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')]);
        }
    });
}

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 但是,当我通过console.log转储imageData时,我的每个元素(应该是包含URL和内容长度的数组)最终为[undefined, XXXX] ,其中XXXX始终是最后请求的Content-Length的大小

I'm stumped, though it appears to be a timing/scoping issue. 我很难过,虽然这似乎是一个时间/范围问题。 Do I have a sort of race-condition occuring here? 我在这里遇到过某种竞争条件吗?

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. 问题是回调函数捕获的单个变量iajaxSizeRequest对于回调函数的所有实例都是相同的变量。 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. 我想如果你调用一个函数并将索引变量传递给它,同时 将请求变量本地范围扩展到函数本身 使用done处理程序的响应参数,你最终应该得到回调捕获的独立变量。 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')]);
    });
}

looks like your i isnt properly closed-in 看起来你的i正确封闭

in addition, you can't use ajaxSizeRequest because it too is pointing to just one request (probably the last, because the loop will execute very fast) 另外,你不能使用ajaxSizeRequest因为它也只指向一个请求(可能是最后一个,因为循环执行速度非常快)

just wrap your success callback function as follows, changing the reference to ajaxSizeRequest : 只需将您的success回调函数包装如下,更改对ajaxSizeRequest的引用:

success: (function(i){
   return function(data,status,xhr){
     imageData.push([imageTemp[i], xhr.getResponseHeader('Content-Length')]);
   };
})(i)

You can scope I like so: 您可以这样做我喜欢的范围:

success: function(i){
    return function(message){
        imageData.push([imageTemp[i], ajaxSizeRequest.getResponseHeader('Content-Length')]);
    }
}(i)

If anyone still having trouble with this, and since this post is, like, 5 years-old already, here's a more 'modern' version of the answer: just use let instead of var in the original post's for loop. 如果有人仍然遇到这个问题,并且由于这篇帖子已经有5年之久了,这里的答案就更加“现代”了:只需在原始帖子中使用let而不是var for循环。

Info: Is there any reason to use the “var” keyword in ES6? 信息: 有没有理由在ES6中使用“var”关键字? and: MDN - Let syntax 和: MDN - 让语法

You have a single i variable which is shared by all of the callbacks. 你有一个i变量,它由所有回调共享。
Since AJAX is asynchronous, all of the callbacks run after your loop is finished, and they all get the same i . 由于AJAX是异步的,所以所有回调都在循环结束后运行,并且它们都得到相同的i

To fix this, you need to move the AJAX call into a separate function that takes i as a parameter. 要解决此问题,您需要将AJAX调用移动到一个单独的函数中,该函数将i作为参数。
Thus, each callback will get a separate i parameter. 因此,每个回调将获得一个单独的i参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM