XMLHttpRequest onload在完成后会破坏响应吗?

时间:2016-08-03 21:51:51

标签: javascript xmlhttprequest

我尝试将多个xhr响应打包成zip文件,然后再下载

问题是,当xhr.onload完成后,我对响应的引用被破坏了......似乎我在这个函数中制作的任何深拷贝都被破坏了。

有任何解决方法吗?

                    var zip = new JSZip();
                    objs.each(function() {
                        var fileName = this.id;
                        var link = this.value;
                        xhr.open('GET', link, true);
                        xhr.responseType = 'arraybuffer';
                        xhr.onload = function(e) {
                            zip.file(fileName, this.response);
                        };
                        xhr.send(null);
                    });
                    zip.generateAsync({type:"blob"}).then(function (blob) {
                        saveAs(blob, "hello.zip");
                    });

1 个答案:

答案 0 :(得分:0)

在这种情况下,Promises将会大放异彩:

public TableLayoutPanel tableLayoutPanel { get; set; }

private void Form_Load(object sender, EventArgs e)
{
    foreach (Panel space in this.tableLayoutPanel.Controls)
    {
        space.MouseClick += new MouseEventHandler(clickOnSpace);
    }
}

public void clickOnSpace(object sender, MouseEventArgs e)
{

    MessageBox.Show("Cell chosen: (" + 
                     tableLayoutPanel.GetRow((Panel)sender) + ", " + 
                     tableLayoutPanel.GetColumn((Panel)sender) + ")");
}

JSZip(v3 +)支持数组缓冲区,但也支持数组缓冲区。 function urlToPromise(url) { return new Promise(function(resolve, reject) { // create a new xhr each time var xhr = new XMLHttpRequest(); xhr.onload = function(e) { resolve(this.response); }; xhr..... // set the other fields, call send(), etc }; } var zip = new JSZip(); objs.each(function() { var fileName = this.id; var link = this.value; zip.file(fileName, urlToPromise(link)); }); zip.generateAsync({type:"blob"}).then(function (blob) { saveAs(blob, "hello.zip"); }); 通过获取来自url创建承诺,urlToPromise将在内部等待所有ajax调用解析。