简体   繁体   English

将xhr.responseURL保存到数组

[英]Save xhr.responseURL to array

I have an array of URLs that i need to find the redirects for. 我有一个URL数组,我需要为其找到重定向。 I have been using XMLHttpRequest / xhr.responseURL to do so. 我一直在使用XMLHttpRequest / xhr.responseURL来做到这一点。 When I print the results to the console, the redirected URLs display as expected. 当我将结果打印到控制台时,重定向的URL将按预期显示。 However, when I try to save those redirected URLs to an array, the array remains empty. 但是,当我尝试将那些重定向的URL保存到数组时,该数组保持为空。 How can I save them to the array? 如何将它们保存到阵列?

Updated with code 用代码更新

var imageDestinations = [];

function imageDestinationGrabber(imageSource) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', imageSource, true);
    xhr.onload = function() {
    imageDestinations.push(xhr.responseURL).trim());
    console.log((xhr.responseURL).trim());
    };
    xhr.send(null);
}

The console log works, but the array remains empty. 控制台日志可以工作,但是该阵列保持为空。

You had a couple syntax issues that was breaking your code. 您遇到了一些语法问题,这些问题破坏了代码。 You had an extra parenthesis at the end of your array push. 在数组推送结束时,您需要加上一个括号。

imageDestinations.push(xhr.responseURL).trim());

That is trying to .trim() the .push() call 那是试图.trim() .push()调用

Here's the fixed code: 这是固定代码:

 var imageDestinations = []; function imageDestinationGrabber(imageSource) { var xhr = new XMLHttpRequest(); xhr.open('GET', imageSource, true); xhr.onload = function() { imageDestinations.push( xhr.responseURL.trim() ); console.log( xhr.responseURL.trim() ); }; xhr.send(null); } 

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

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