從JavaScript 程式碼呼叫Python 函數
在JavaScript 缺乏滿足特定需求的必要功能的情況下,有必要探索這種可能性將Python 函數整合到JavaScript 程式碼中。本文旨在透過引導您完成建立此類連接的過程並提供有效完成此任務的修改後的程式碼片段來滿足此需求。
初始JavaScript 程式碼:
提供的JavaScript 程式碼如下所示,表示呼叫Python 函數的初始嘗試:
<code class="javascript">var tag = document.getElementsByTagName("p")[0]; text = tag.innerHTML; // Here I would like to call the Python interpreter with Python function arrOfStrings = openSomehowPythonInterpreter("~/pythoncode.py", "processParagraph(text)");</code>
Python 腳本(~/pythoncode.py):
<code class="python">import nltk # is not in JavaScript def processParagraph(text): ... nltk calls ... return lst # returns a list of strings (will be converted to JavaScript array)</code>
解決方案:對Python 腳本的AJAX 請求
<code class="javascript">$.ajax({ type: "POST", url: "~/pythoncode.py", data: { param: text} }).done(function( o ) { // do something });</code>
以上是如何從 JavaScript 程式碼呼叫 Python 函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!