JSON文件下载期间出错

时间:2018-04-16 21:26:27

标签: javascript json

我正在尝试使用下面提到的代码将JSON数据下载到JSON文件中,但代码只是给了我一个空白的Internet Explorer。我需要代码来下载JSON文件,而不会在用户界面上引发任何事件。

 var dataUri = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(JSONData));
    var downloadAnchorNode = document.createElement('a');
    downloadAnchorNode.setAttribute("href", dataUri);
    downloadAnchorNode.setAttribute("download", "CarData.json");
    downloadAnchorNode.click();

1 个答案:

答案 0 :(得分:0)

您将获得一个空白页面,因为您没有将锚节点插入DOM。请考虑以下代码段。即使您删除download属性,也会转到包含JSON数据的页面。

var JSONData = {
  foo: "bar"
};

var dataUri = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(JSONData));
var downloadAnchorNode = document.createElement('a');

downloadAnchorNode.innerHTML = "Click";
downloadAnchorNode.setAttribute("href", dataUri);
downloadAnchorNode.setAttribute("download", "CarData.json");
document.body.appendChild(downloadAnchorNode);

downloadAnchorNode.click();

这里没有download

var JSONData = {
  foo: "bar"
};

var dataUri = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(JSONData));
var downloadAnchorNode = document.createElement('a');

downloadAnchorNode.innerHTML = "Click";
downloadAnchorNode.setAttribute("href", dataUri);
document.body.appendChild(downloadAnchorNode);

downloadAnchorNode.click();

此外,正如其他人所指出的,IE does not support the download attribute