【问题标题】:Why are console.log() and alert() returning different information? [closed]为什么 console.log() 和 alert() 返回不同的信息? [关闭]
【发布时间】:2021-04-27 21:27:08
【问题描述】:

我在 JavaScript 中有以下代码,它采用指向图像的 URL,并使用 fetch()FileReader() 来获取图像的数据作为数据 URL。

fetch(document.getElementById("image-url").value).then(res => res.blob()).then(data => {
    let reader = new FileReader();
    reader.onload = function() {
        alert(this.result.toString());
        console.log(this.result.toString());
    };
    reader.readAsDataURL(data);
});

但是,alert() 返回的内容与 console.log() 返回的内容不同。 (我尝试包含alert()console.log() 的图像数据,但它不会让我,因为它们太长了。)

当我在浏览器中从alert() 加载图像数据时,它返回“无效 URL”,而第二个返回原始图像数据(即它可以工作)。我错过了什么?我打算把这张图片数据上传到服务器上供以后使用,但是上传的数据和alert()一样,用处不大。

【问题讨论】:

    标签: javascript fetch filereader


    【解决方案1】:

    alert() 只能处理字符串。 console.log() 可以处理对象和字符串。

    console.log() vs. alert() when debugging

    const foo = {};
    alert(foo);

    【讨论】:

    • .toString 在 OP 的代码中让我觉得这个问题的根源是不同的。该问题缺少相关信息,因此无法正确回答。
    • 根据MDNthis.result 是一个字符串。
    • @detectiveCamel:是什么导致了带有 alert() 的“无效 URL”消息?
    • 运行我为你添加的sn-p。 alert 接受任何带有 toString() 方法的参数。您链接的文章指出,虽然您可以提醒对象,但如果通过 console.log 进行日志记录,则生成的输出更有用。
    • @JohnH 浏览器通常可以获取格式化为数据 URL 的图像数据并输出图像。当我尝试查看图像数据alerted 时,我的浏览器返回“无效 URL”。但是,当我尝试查看记录的图像数据时,图像弹出得很好。
    猜你喜欢
    • 2022-01-19
    • 2022-01-19
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    相关资源
    最近更新 更多