简体   繁体   中英

How do I get 'Content-Length' via javascript?

I have the following snippet:

var size;
function getImageSize(url) 
{
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', url, true);
    xhr.onreadystatechange = function() 
    {
        if (xhr.readyState == 4) 
        {
            if (xhr.status == 200) 
            {
                size = xhr.getResponseHeader('Content-Length');
                alert(size);
            }
        }
    };
    xhr.send(null);
    return size;
}

The purpose of the function is to return the file size (of a image).

The alert inside the function will always return the correct value, however the function itself will always return undefined . Why?

Odly, if I debug it with firebug, the function will always return correctly...

That's because the function returns before the response is returned and the size is set. It's namely executed asynchronously. You'd like to pass a callback function instead and apply it with size as argument.

Well you have a code order problem there, that code is not synchronous, it is asynchronous.

The callback happens in the future, whereas the return happens straight away.

The reason debugging it in Firebug results in the return being correct, is that slows the code down long enough for the callback to have executed before you get to the return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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