javascript - 将 xhr.responseURL 保存到数组

标签 javascript arrays url xmlhttprequest-level2

我有一组 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/

相关文章:

javascript - 如何通过javascript在随机位置但在特定宽度和高度内附加div来定位一张图像?

javascript - 如何将特定本地主机路由中的 json 对象分配给 javascript 中的变量

php 从数组中删除一项

javascript - 使用ajax将数组数据从浏览器中的javascript传递到spring mvc Controller

url - 是否可以使用 URL 参数链接到 PDF 中的书签?

javascript - 热门构建 20 多个页面中使用的 SEO 友好的 JavaScript 菜单

javascript - 验证电子邮件是否已成功发送 nodemailer (sails.js)

javascript - 'Delete' 在 JavaScript 中如何工作?

cocoa - 如何使用 Cocoa 将 URL 关联到应用程序

java - 如何使用Config.getPhotoPath()?