【发布时间】:2015-11-14 23:55:59
【问题描述】:
我已经浏览了这个网站上的其他问题,但没有一个有我正在寻找的答案,因为大多数都有 jQuery、JSON、AJAX 的代码(如果我真的可以在下面的 JavaScript 函数中使用它,我'll use it),或者尝试下载一些文件/程序/框架/包来完成它,比如Flask、TkInter或Django,我都不能用。
我需要这样做而不需要额外的文件。
所以我要做的是获取一个名为“删除”的 HTML 按钮,以在单击时删除另一个名为 gallery.cgi 的页面上的图像,而“取消”只是在单击时重定向到 gallery.cgi。 main() 可以做到这一点,但我不能在 HTML/JavaScript 代码中调用它。我只需要在单击“删除”时调用 main()。
这是我试图在 JavaScript 中运行的函数 main(),它使用名为 test_shelf(存储图像目录)和 filename.db(存储文件名)的数据库文件(用于持久存储)。使用它,它会删除存储在 db 文件中的最后一个图像。
import cgi, os
import cgitb; cgitb.enable()
import shelve
images = shelve.open('test_shelf.db', writeback = True)
imageTitle = "Armory" # Title of image being deleted
def main():
db = shelve.open('filename.db', writeback = True)
try:
if db['key']:
alist = db['key'] # read
_filename = alist[-1] # last element of list
images.pop(_filename, None)
alist.remove(_filename)
db['key'] = alist # writeback
if os.path.exists('pictures/' + _filename): # pictures is where I store the images, so I need to delete them.
os.remove('pictures/' + _filename)
finally:
db.close()
这是我要在其中调用 python 函数的 JavaScript 函数。
function deletePicture() {
// Call main() here, so only clicking "Delete" button can delete an image
location.href='gallery.cgi';
}
这是调用 deletePicture() OnClick 的 HTML 代码。名为 Delete 的按钮在单击时调用 deletePicture(),它应该调用 main(),它将删除存储在 db 中的最后一张图像,然后重定向到 gallery.cgi。
<p>Are you sure? You want to delete picture [ <b>"""
print imageTitle
print """</b> ].</p>
<input type = "button" value = "Delete" onClick = "return deletePicture()"/>
<input type = "button" value = "Cancel" onClick = "location.href='gallery.cgi';"/>
请注意,所有这些都在同一个文件 (delete.cgi) 中,这是一个 Python CGI。所有 HTML/JavaScript 代码均由 python 代码打印。 (我不能创建另一个具有 main() 代码的文件(.py)然后在 delete.cgi 中调用它,我只能使用一个 .cgi 文件来执行删除。)
【问题讨论】:
标签: javascript python html cgi