如何在 Javascript 中动态创建要下载的文档? [英] How do I dynamically create a document for download in Javascript?

查看:26
本文介绍了如何在 Javascript 中动态创建要下载的文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些在客户端生成 XML 文档的 Javascript 代码(通过 Google 地球插件).我希望用户能够单击页面上的按钮并被提示将该 XML 保存到新文件中.如果我生成 XML 服务器端,这将很容易,只需让按钮打开链接即可.但是 XML 是在客户端生成的.

I'm writing some Javascript code that generates an XML document in the client (via Google Earth plugin). I'd like the user to be able to click a button on the page and be prompted to save that XML to a new file. If I were generating the XML server-side this would be easy, just make the button open the link. But the XML is generated client-side.

我提出了一些半途而废的技巧,部分灵感来自 这个 StackOverflow 问题.但两者都不能完全奏效.这是一个带有嵌入代码的演示 HTML:

I've come up with a couple of hacks that half-work, inspired in part by this StackOverflow question. But neither completely work. Here's a demo HTML with embedded code:

<html><head><script>
function getData() { return '<?xml version="1.0" encoding="UTF-8"?><doc>Hello</doc>'; }
function dlDataURI() {
  window.open("data:text/xml;charset=utf-8," + getData());
}
function dlWindow() {
  var w = window.open();
  w.document.open();
  w.document.write(getData());
  w.document.close();
}
</script><body>
<div onclick="dlDataURI()">Click for Data URL</div>
<div onclick="dlWindow()">Click for Window</div>
</body></html>

dlDataURI() 版本在 Firefox 中效果很好,在 Chrome 中效果不佳(无法保存),而在 IE 中则完全没有.Window() 版本在 Firefox 和 IE 中工作正常,但在 Chrome 中效果不佳(无法保存,XML 嵌入在 HTML 中).两个版本都不会提示用户下载,它总是会打开一个新窗口来尝试显示 XML.

The dlDataURI() version works great in Firefox, poorly in Chrome (can't save), and not at all in IE. The Window() version works OK in Firefox and IE, and not well in Chrome (can't save, XML embedded inside HTML). Neither version ever prompts a user download, it always opens a new window trying to display the XML.

有什么好方法可以在客户端 Javascript 中做我想做的事吗?我希望它可以在当今的浏览器中使用,最好是 Firefox、MSIE 8 和 Chrome.

Is there a good way to do what I want in client side Javascript? I'd like this to work in today's browsers, ideally Firefox, MSIE 8, and Chrome.

使用示例下载代码更新

window.onload = function() {
  Downloadify.create("dlify", {
    data: getData(),
    filename: "data.xml",
    swf: 'media/downloadify.swf',
    downloadImage: 'images/download.png',
    width: 100, height: 30});};

推荐答案

目前我见过的最好的是 Doug Neiner 下载,它需要 Flash 但效果很好:

The best I've seen as far is Downloadify by Doug Neiner, it requires Flash but works very well:

一个微型 JavaScript + Flash 库,无需服务器交互,即可在浏览器中即时生成和保存文件."

"A tiny JavaScript + Flash library that enables the generation and saving of files on the fly, in the browser, without server interaction."

查看此视频.

这篇关于如何在 Javascript 中动态创建要下载的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆