我有一组 URL,需要为其查找重定向。我一直在使用 XMLHttpRequest/xhr.responseURL 来执行此操作。当我将结果打印到控制台时,重定向的 URL 按预期显示。但是,当我尝试将这些重定向的 URL 保存到数组中时,该数组仍为空。如何将它们保存到数组中?
已使用代码更新
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);
}
控制台日志有效,但数组仍为空。
最佳答案
您有几个语法问题破坏了您的代码。您的数组推送末尾有一个额外的括号。
imageDestinations.push(xhr.responseURL).trim());
这是尝试.trim()
.push()
调用
这是固定代码:
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);
}
关于javascript - 将 xhr.responseURL 保存到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35902475/