简体   繁体   English

使用CGI和Javascript保存文件

[英]Use CGI and Javascript to save a file

I have some JSON scripts that I plan on parsing on the site and then allowing the clients to edit them through my interface (to later be loaded and parsed once again for display). 我计划在站点上进行解析的一些JSON脚本,然后允许客户端通过我的界面对其进行编辑(稍后再加载并解析以显示)。 Problem is, Javascript doesn't have access to writing to the file system. 问题是,Javascript无法访问文件系统。 I've already got a system for reading the JSON files using Javascript (and jQuery). 我已经有一个使用Javascript(和jQuery)读取JSON文件的系统。 Now, I've heard I can use CGI to save the data later. 现在,我听说我以后可以使用CGI保存数据。 Can somebody give me some references and in depth explanations? 有人可以给我一些参考和深入的解释吗? I've read a bit about CGI in general but nothing specific. 我已经大致了解了CGI,但没有具体内容。

Thanks for any help! 谢谢你的帮助!

CGI is a way for servers to interface with scripts. CGI是服务器与脚本交互的一种方式。 Pretty much, you just set up the server to execute a file, and it will execute it with several environment variables set and POST data fed to its standard input. 几乎,您只是将服务器设置为执行文件,它将通过设置多个环境变量并将POST数据馈送到其标准输入来执行该文件。 The script should output the headers for the page, followed by the content. 该脚本应输出页面的标题,然后是内容。

CGI scripts can be written in many different languages. CGI脚本可以用许多不同的语言编写。 Perl is well-known for CGI scripts; Perl以CGI脚本而闻名。 it has documentation on it here . 它在这里有文档。 Python has a cgi module to deal with CGI. Python有一个处理CGI cgi模块 Ruby has a CGI package as well. Ruby也有一个CGI

Here's a quick CGI script written in Python that writes to a file. 这是用Python编写的可写入文件的快速CGI脚本。 You'll probably want to modify it or use it as a reference rather than using it as-is: 您可能想要修改它或将其用作参考,而不是按原样使用它:

#!/usr/bin/env python
import os
import os.path
import sys
import json
import cgi
# You'll probably want to remove or alter
# the following line for production.
import cgitb; cgitb.enable()

def bad_request():
    print "Status: 400 Bad Request"
    print "Content-Type: application/json"
    print ""
    json.dump({'success': False}, sys.stdout)
    sys.exit(0)

assert 'REQUEST_METHOD' in os.environ
if os.environ['REQUEST_METHOD'] != 'POST':
    bad_request()

form = cgi.FieldStorage()
if 'data' not in form:
    bad_request()

filename = os.path.join(os.path.dirname(__file__), "some_file.json")
with open(filename, "wb") as f:
    f.write(form['data'].value)

print "Content-Type: application/json"
print ""
json.dump({'success': True}, sys.stdout)

If you POST to it with a data parameter, it will save that data into some_file.json in the same directory as itself. 如果使用data参数对其进行POST ,它将把该data保存到与自身相同的目录中的some_file.json中。

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

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