【问题标题】:How do download of Json using Fetch in JavaScript?如何在 JavaScript 中使用 Fetch 下载 Json?
【发布时间】:2017-10-17 19:30:07
【问题描述】:

如何从 Fetch URL 下载所需的 JSON?

在 XLSX 中下载。

代码

function teste (){

alert(fetch ("url")        
.then(response => response.json())
.then(data => { console.log(data)})
     .then(response => response.blob())
        .then(blob => {
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = "filename.xlsx";
            a.click();                    
        })
)
}

【问题讨论】:

  • alert() 的目的是什么?第二个.then()没有返回值
  • 好吧,一方面,第一个.then() 没有传播data,这意味着第二个.then()responseundefined
  • 为了做一个测试,我不知道它是否正确它是形式。

标签: javascript json fetch


【解决方案1】:

.then() 中删除alert()return 值。注意Response只能读取一次

function teste() {   
  fetch("url")
    .then(async(response) => {
      let clone = response.clone();
      let res = await clone.json();
      console.log(res);
      return response.blob()
    })
    .then(blob => {
      var url = window.URL.createObjectURL(blob);
      var a = document.createElement('a');
      a.href = url;
      a.download = "filename.xlsx";
      a.click();
    })
    .catch(function(err) {
      console.error(err)
    })
}

【讨论】:

  • @JeanCarlos 注意,动态创建的<a> 元素应附加到document.bodyDOM 中的其他现有元素,以便代码在Firefox 上呈现相同的结果。 Chromium,Chrome 启动 Save File 对话框,而无需将动态创建的 <a> 元素显式附加到 document
猜你喜欢
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 2018-02-03
  • 1970-01-01
  • 2020-10-04
  • 2020-12-29
  • 2021-08-03
  • 2021-07-06
相关资源
最近更新 更多