简体   繁体   English

在javascript中生成一些xml,提示用户保存它

[英]Generate some xml in javascript, prompt user to save it

I'd like to make an XML document in JavaScript then have a save dialog appear. 我想在JavaScript中创建一个XML文档,然后出现一个保存对话框。

  1. It's OK if they have to click before the save can occur. 如果在保存发生之前必须单击它们就可以了。
  2. It's *not* OK if I *have* to use IE to achieve this (I don't even need to support it at all). 如果我*使用IE来实现这一点(我甚至根本不需要支持它),这不是* OK。 However, Windows is a required platform (so Firefox or Chrome are the preferred browsers if I can only do this in one browser). 但是,Windows是必需的平台(因此,如果我只能在一个浏览器中执行此操作,则Firefox或Chrome是首选的浏览器)。
  3. It's *not* OK if I need a web server. 如果我需要一台网络服务器,那就不行了。 But conversely, I don't want to require the JavaScript to be run on a local file only, ie elevated privileges -- if possible. 但相反,我不想要求JavaScript只在本地文件上运行,即提升权限 - 如果可能的话。 That is, I'd like to to run locally or on a *static* host. 也就是说,我想在本地运行或在* static *主机上运行。 But just locally is OK. 但只是在当地是可以的。
  4. It's OK to have to bend over backwards to do this. 可以向后弯腰来做这件事。 The file won't be very big, but internet access might either be there, be spotty or just not be a possibility at all -- see (3). 该文件不会很大,但互联网访问可能在那里,不稳定或根本不可能 - 见(3)。

So far the only ideas I have seen are to save the XML to an iframe and save that document -- but it seems that you can only do this in IE? 到目前为止,我看到的唯一想法是将XML保存到iframe并保存该文档 - 但似乎你只能在IE中执行此操作? Also, that I could construct a data URI and place that in a link. 此外,我可以构建一个数据URI并将其放在一个链接中。 My fear here is that it will just open the XML file in the window, rather than prompt the user to save it. 我担心的是它只会在窗口中打开XML文件,而不是提示用户保存它。

I know that if I require the JavaScript to be local, I can raise privileges and just directly save the file (or hopefully cause a save dialog box to appear). 我知道如果我要求JavaScript是本地的,我可以提高权限并直接保存文件(或者希望导致出现保存对话框)。 However, I'd much prefer a solution where I do not require raised privileges (even a Firefox 3.6 only solution). 但是,我更喜欢一个我不需要提升权限的解决方案(即使只有Firefox 3.6解决方案)。

I apologize if this offends anyone's sensibilities (for example, not supporting every browser). 如果这会冒犯任何人的敏感性(例如,不支持每个浏览器),我会道歉。 I basically want to write an offline application and Javascript/HTML/CSS seem to be the best candidate considering the complexity of the requirements and the time available. 我基本上想要编写一个离线应用程序,考虑到需求的复杂性和可用的时间,Javascript / HTML / CSS似乎是最佳候选者。 However, I have this single requirement of being able to save data that must be overcome before I can choose this line of development. 但是,我有这个能够保存必须克服的数据的单一要求,然后才能选择这条开发线。

How about this downloadify script? 这个downloadify脚本怎么样?

Which is based on Flash and jQuery, which can prompt you dialog box to save file in your computer. 这是基于Flash和jQuery的,它可以提示您在计算机中保存文件的对话框。

Downloadify.create('downloadify',{
  filename: function(){
    return document.getElementById('filename').value;
  },
  data: function(){ 
    return document.getElementById('data').value;
  },
  onComplete: function(){ 
    alert('Your File Has Been Saved!'); 
  },
  onCancel: function(){ 
    alert('You have cancelled the saving of this file.');
  },
  onError: function(){ 
    alert('You must put something in the File Contents or there will be nothing to save!'); 
  },
  swf: 'media/downloadify.swf',
  downloadImage: 'images/download.png',
  width: 100,
  height: 30,
  transparent: true,
  append: false
});

Using a base64 encoded data URI, this is possible with only html & js. 使用base64编码的数据URI,只有html和js才有可能。 What you can do is encode the data that you want to save (in your case, a string of XML data) into base64, using a js library like jquery-base64 by carlo . 您可以做的是使用js库(如jquery-base64 by carlo )将要保存的数据(在您的情况下,一串XML数据)编码到base64中。 Then put the encoded string into a link, and add your link to the DOM. 然后将编码的字符串放入链接,并将链接添加到DOM。

Example using the library I mentioned (as well as jquery): 使用我提到的库(以及jquery)的示例:

<html>
<head>
    <title>Example</title>
</head>
<body>
    <script>
        //include jquery and jquery-base64 here (or whatever library you want to use)
        document.write('<a href="data:application/octet-stream;base64;charset=utf-8,' + $.base64.encode( "this is a example, which requires the jquery-base64 library to work... replace this text with your xml" ) + '">click to make save dialog</a>');
    </script>
</body>
</html>

...and remember to make the content-type something like application/octet-stream so the browser doesn't try to open it. ...并且记得使内容类型类似于application/octet-stream因此浏览器不会尝试打开它。

Warning: some older IE versions don't support base64, but you said that didn't matter, so this should work fine for you. 警告:一些较旧的IE版本不支持base64,但你说没关系,所以这应该适合你。

Without any more insight into your specific requirements, I would not recommend a pure Javascript/HTML solution. 如果不了解您的具体要求,我不建议使用纯Javascript / HTML解决方案。 From a user perspective you would probably get the best results writing a native application. 从用户的角度来看,您可能会在编写本机应用程序时获得最佳结果。 However if it will be faster to use Javascript/HTML, I recommend using a local application hosting a lightweight web server to serve up your content. 但是,如果使用Javascript / HTML会更快,我建议使用托管轻量级Web服务器的本地应用程序来提供您的内容。 That way you can cleanly handle the file saving server-side while focusing the bulk of your effort on the front-end application. 这样,您可以干净地处理文件保存服务器端,同时将大部分精力集中在前端应用程序上。

You can code up a web server in - for example - Python or Ruby using very few lines of code and without 3rd party libraries. 您可以使用非常少的代码行和没有第三方库来编写Web服务器 - 例如 - Python或Ruby。 For example, see: 例如,请参阅:


"""
Serves files out of its current directory.
Doesn't handle POST requests.
"""
import SocketServer
import SimpleHTTPServer

PORT = 8080

def move():
    """ sample function to be called via a URL"""
    return 'hi'

class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        #Sample values in self for URL: http://localhost:8080/jsxmlrpc-0.3/
        #self.path  '/jsxmlrpc-0.3/'
        #self.raw_requestline   'GET /jsxmlrpc-0.3/ HTTP/1.1rn'
        #self.client_address    ('127.0.0.1', 3727)
        if self.path=='/move':
            #This URL will trigger our sample function and send what it returns back to the browser
            self.send_response(200)
            self.send_header('Content-type','text/html')
            self.end_headers()
            self.wfile.write(move()) #call sample function here
            return
        else:
            #serve files, and directory listings by following self.path from
            #current working directory
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

httpd = SocketServer.ThreadingTCPServer(('localhost', PORT),CustomHandler)

print "serving at port", PORT
httpd.serve_forever()

Finally - Depending on who will be using your application, you also have the option of compiling a Python program into a Frozen Binary so the end user does not have to have Python installed on their machine. 最后 - 根据谁将使用您的应用程序,您还可以选择将Python程序编译为Frozen Binary,以便最终用户不必在其计算机上安装Python。

Javascript is not allowed to write to a local machine. Javascript不允许写入本地计算机。 Your question is similar to this one . 你的问题和这个问题类似。

I suggest creating a simple desktop app. 我建议创建一个简单的桌面应用。

Why not use a hybrid flash for client and some server solution server-side. 为什么不在服务器端和服务器端服务器端使用混合闪存。 Most people have flash so you can default to client side to conserve resources on the server. 大多数人都有闪存,因此您可以默认使用客户端来节省服务器上的资源。

Are you looking for something like this ? 您是否在寻找像这样

If PHP is ok, if would be much easier. 如果PHP没问题,那将更容易。

Is localhost PHP server ok? localhost PHP服务器可以吗? Web traditionally can't save to hard drive because of security concerns. 由于安全问题,Web传统上无法保存到硬盘驱动器。 PHP can push files though it requires a server. 虽然PHP需要服务器,但它可以推送文件。

Print to PDF plugins are available for available for all browsers. 打印到PDF插件可供所有浏览器使用。 Install once, print to PDF forever. 安装一次,永久打印到PDF。 Then, you can use a javascript or Flash to call a Print function. 然后,您可以使用javascript或Flash调用打印功能。

Also, if you are developing for an environment where internet access is spotty, conwider using VB.NET or some other desktop language. 此外,如果您正在开发一个互联网访问不稳定的环境,使用VB.NET或其他一些桌面语言。

EDIT: 编辑:

You can use the browser's Print function. 您可以使用浏览器的打印功能。

With IE you could use document.execCommand, but I note that IE is not an option. 使用IE,您可以使用document.execCommand,但我注意到IE不是一个选项。

Here's something that looks like it might help, although it will not prompt with SaveAs dialog, https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FOL . 这里看起来可能会有所帮助,虽然它不会提示使用SaveAs对话框, https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FOL

One simple but odd way to do this that doesn't require any Flash is to create an <a/> with a data URI for its href . 执行此操作的一个简单但奇怪的方法是不需要任何Flash,就是为其href创建一个带有数据URI<a/> This even has pretty good cross-browser support, although for IE it must be at least version 8 and the URI must be < 32k. 这甚至具有相当好的跨浏览器支持,但对于IE,它必须至少是版本8并且URI必须<32k。 It looks like someone else on SO has more to say on the topic. 看起来SO 上的其他人对这个主题有更多的话要说

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

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