如何生成xml文件并允许用户使用javascript在本地保存?

时间:2023-01-14 11:59:38

I am generating a XMl document via JavaScript and need to prompt the user to save it to their local machine.

我正在通过JavaScript生成XMl文档,需要提示用户将其保存到本地计算机。

This is the code I have at the moment:

这是我目前的代码:

var xmlWindow = window.open("", "");
xmlWindow.document.write("<node>data</node>");

This writes the xml to a new window which the user can then hit file->save to download.

这会将xml写入一个新窗口,然后用户可以点击文件 - >保存下载。

  1. Is there any more elegent way of doing this?
  2. 有没有更多的方式这样做?

  3. Is there any way to set the mimeType of the new window so the xml displays properly?
  4. 有没有办法设置新窗口的mimeType,以便xml正确显示?

  5. is there any way to specify the title so when the user hits save, the file name is set correctly?
  6. 有没有办法指定标题所以当用户点击保存时,文件名是否设置正确?

note: needs to be compatible with most brosers (IE6, IE7, FF, Chrome).

注意:需要与大多数提示器兼容(IE6,IE7,FF,Chrome)。

2 个解决方案

#1


You could send the XML through an XMLHttpRequest to a script on your server to make the xml file, then set window.location to the location of your new xml file. They'll be prompted to save it.

您可以通过XMLHttpRequest将XML发送到服务器上的脚本以生成xml文件,然后将window.location设置为新xml文件的位置。他们会被提示保存它。

#2


"save it locally": A tough call, if you want to be compatible across browsers. See this post.

“在本地保存”:如果你想在浏览器之间兼容,那就是一个艰难的电话。看这篇文章。

TiddlyWiki manages to do this for some browsers (not sure which ones it supports) but only by having the user install certain files.

TiddlyWiki设法为某些浏览器执行此操作(不确定它支持哪些浏览器),但只能让用户安装某些文件。

#1


You could send the XML through an XMLHttpRequest to a script on your server to make the xml file, then set window.location to the location of your new xml file. They'll be prompted to save it.

您可以通过XMLHttpRequest将XML发送到服务器上的脚本以生成xml文件,然后将window.location设置为新xml文件的位置。他们会被提示保存它。

#2


"save it locally": A tough call, if you want to be compatible across browsers. See this post.

“在本地保存”:如果你想在浏览器之间兼容,那就是一个艰难的电话。看这篇文章。

TiddlyWiki manages to do this for some browsers (not sure which ones it supports) but only by having the user install certain files.

TiddlyWiki设法为某些浏览器执行此操作(不确定它支持哪些浏览器),但只能让用户安装某些文件。