【问题标题】:Save xhr.responseURL to array将 xhr.responseURL 保存到数组
【发布时间】:2016-06-24 11:17:10
【问题描述】:

我有一组需要查找重定向的 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()); 行的括号看起来不正确,也许应该是imageDestinations.push(xhr.responseURL.trim());

标签: javascript arrays url xmlhttprequest-level2


【解决方案1】:

您有几个语法问题正在破坏您的代码。您在数组推送的末尾有一个额外的括号。

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);
}

【讨论】:

  • 感谢您指出这一点。我更新了它,但我仍然遇到同样的问题。
猜你喜欢
  • 2018-01-08
  • 2011-07-05
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 2010-12-31
  • 2020-10-24
相关资源
最近更新 更多