簡體   English   中英

可以使用JavaScript函數調用Python函數嗎?

[英]Can you call a Python Function using a JavaScript function?

我瀏覽了該網站上的其他問題,但沒有一個問題能找到我想要的答案,因為大多數問題都有jQuery,JSON,AJAX的代碼(如果我可以在下面的JavaScript函數中實際使用它,我將使用),或嘗試下載一些文件/程序/框架/軟件包來執行此操作,例如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';
}

這是HTML中的調用deletePicture()OnClick的代碼。 名為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文件來執行刪除操作。)

我認為您可以通過將刪除輸入連接到gallery.cgi / main /,然后在CGI文件中執行os.environs ['PATH']作為方法來調用main。

HTML:

<input type = "button" value = "Delete" onClick = "location.href='gallery.cgi/main/'"/>

Python(類似):

if os.environs['PATH']:
    path = os.environs['PATH']
    locals()[path]()

如果這是輸入的唯一功能,則也可以將它們替換為鏈接和href。 而且您還想檢查os.environs ['PATH']是否可以運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM