简体   繁体   English

为什么JavaScript中的saveAs()对我不起作用?

[英]Why saveAs() in JavaScript does not work for me?

I need to save a graph to a JSON file. 我需要将图形保存到JSON文件。 Before doing that, I wrote a very simple HTML/JavaScript to test it out (just use a simple string for the JSON). 在此之前,我编写了一个非常简单的HTML / JavaScript对其进行测试(只需对JSON使用一个简单的字符串)。

Based on the suggestion in a Stack Overflow posting, I use saveAs() method. 根据Stack Overflow发布中的建议,我使用saveAs()方法。 But it looks like saveAs() does not work and no file is created. 但看起来saveAs()无法正常工作,也没有创建文件。 I am using Internet Explorer and Window 10. 我正在使用Internet Explorer和Window 10。

In order to debug it, I inserted 3 window.alert() calls. 为了调试它,我插入了3个window.alert()调用。 The first 2 window.alert() calls pop up correctly, however, the 3rd window.alert() call does not show up at all. 前两个window.alert()调用正确弹出,但是第三个window.alert()调用根本不显示。 So I am afraid that the code is aborted at the saveAs() call. 因此,恐怕代码在saveAs()调用中止。

The following is my code: 以下是我的代码:

<html>
<head>
<title>Save</title>
<script>

function save() 
{ 
window.alert("I am here 1");
var jsonBlob = new Blob([JSON.stringify("kiki")], { type: 'application/javascript;charset=utf-8' });
window.alert("I am here 2");
saveAs(jsonBlob, "testout.json");
window.alert("I am here 3");
} 

</script> 
</head>
<body> 
<form name="myform"> 
<input type="button" onClick="save();" value="Save">
</form> 
</body>
</html>

I am wondering why saveAs() does not work for me? 我想知道为什么saveAs()对我不起作用? Am I missing something here? 我在这里想念什么吗? Do I need to add something to my computer in order to use saveAs() method? 我是否需要在计算机上添加某些内容才能使用saveAs()方法?

Thank you very much for your advice! 非常感谢您的建议!

You are a little bit error in saveAs. 您在saveAs中有点错误。 Code is given below: 代码如下:

 <html>
    <head>
    <title>Save</title>
    <script>

    function save() 
    { 
    window.alert("I am here 1");
    var jsonBlob = new Blob([JSON.stringify("kiki")], { type: 'application/javascript;charset=utf-8' });
    window.alert("I am here 2");
   var link=window.URL.createObjectURL(jsonBlob);
    window.location=link;
    window.alert("I am here 3");
    } 

    </script> 
    </head>
    <body> 
    <form name="myform"> 
    <input type="button" onClick="save();" value="Save">
    </form> 
    </body>
    </html>

Also you can see this: http://eligrey.com/demos/FileSaver.js/ 您也可以看到以下内容: http : //eligrey.com/demos/FileSaver.js/

Convert into excel sheet using JavaScript 使用JavaScript转换为Excel工作表

var excelBlob = new Blob([response], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, "excel.xlsx");     
var link=window.URL.createObjectURL(excelBlob);
window.location=link;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM