JS - (异步)XHR和增量

时间:2015-02-21 18:14:28

标签: javascript ajax xmlhttprequest blob increment

关于SO的第一篇文章,但实际上是一位长期用户,因为我已经找到了我需要的所有东西......直到现在。

我正面临着XHR的棘手问题。我可能会说我是JS的新手,但我没想到会发生这样的事情,我无法绕过...

所以问题是我正在远程服务器上用“for”循环检索一堆图像。没问题,它有效。但是我想给他们一个id,以便在他们的“数字”之后使用它们,这样我就可以在画布中使用它们,并为它制作动画。我不知道问题出在哪里但是id的增加出错了。这是我的代码:

<body>

<button onclick="loadCanvas(113);">Click here</button>
<canvas id="targetedCanvas" width="768" height="512"></canvas>
<script>
    window.URL = window.URL || window.webkitURL;        

    function loadImages() {
        for (id = 0; id < 114; id++) {
            var url = 'http://myurl.com/IMG_'+id+'.JPG';
            var request = new XMLHttpRequest();
            request.open('GET', url, true);
            request.responseType = 'blob';
            request.onload = function(e) {
                if(this.status == 200) {
                    var blob = this.response;

                    var img = document.createElement('img');
                    img.id = id;
                    img.onload = function(e) {
                        window.URL.revokeObjectURL(img.src);
                    };
                    img.src = window.URL.createObjectURL(blob);
                    img.width = 0;
                    img.height = 0;
                    document.body.appendChild(img);
                    }
                }
            request.send(null);
            };
    }

    function loadCanvas(id) {
        var canvas = document.getElementById('targetedCanvas');
        var context = canvas.getContext('2d');
        var img = document.getElementById(id);
        context.drawImage(img,0,0);
    };

    loadImages();

</script>
</body>

所以你看到有一个按钮,当你点击它时,它会将图像加载到画布上以显示它。 当我想显示id(console.log(id);)时,id.inload函数中的id是正常的(我的意思是,它类似于1,2,3 ......)但是在函数内部它始终是113.这个是我无法理解的事情。我想这是因为XHR是异步的,或类似的......这就是我真正的新手......

然后,如果有人有钥匙,或知道某些事情要以另一种方式使用XHR加载的图像,我会很高兴看到它! :)

非常感谢SO社区!

1 个答案:

答案 0 :(得分:0)

您需要使用self invoking function并在该函数中传递id

因为请求本质上是异步的,所以直到你得到一个单独的响应时,for循环将完成并且id将射到114并且所有分配的id将(可能)是114.所以保留它自己调用函数。

 function loadImages() {
        for (id = 0; id < 114; id++) {
            (function(id){
            var url = 'http://myurl.com/IMG_'+id+'.JPG';
            var request = new XMLHttpRequest();
            request.open('GET', url, true);
            request.responseType = 'blob';
            request.onload = function(e) {
                if(this.status == 200) {
                    var blob = this.response;

                    var img = document.createElement('img');
                    img.id = id;
                    img.onload = function(e) {
                        window.URL.revokeObjectURL(img.src);
                    };
                    img.src = window.URL.createObjectURL(blob);
                    img.width = 0;
                    img.height = 0;
                    document.body.appendChild(img);
                    }
                }
            request.send(null);
            })(id);
            };
    }