从 JavaScript 代码调用 Python 函数 [英] Call Python function from JavaScript code
问题描述
我想从 JavaScript 代码中调用 Python 函数,因为 JavaScript 中没有替代方案来执行我想要的操作.这可能吗?你能调整下面的代码片段吗?
I'd like to call a Python function from JavaScript code, because there isn't an alternative in JavaScript for doing what I want. Is this possible? Could you adjust the below snippet to work?
JavaScript 代码:
JavaScript code:
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)");
~/pythoncode.py
包含使用高级库的函数,这些函数在 JavaScript 中没有易于编写的等效项:
~/pythoncode.py
contains functions using advanced libraries that don't have an easy to write equivalent in JavaScript:
import nltk # is not in JavaScript
def processParagraph(text):
...
nltk calls
...
return lst # returns a list of strings (will be converted to JavaScript array)
推荐答案
您需要做的只是向您的 Python 代码发出 ajax 请求.你可以用 jquery http://api.jquery.com/jQuery.ajax/ 做到这一点,或者只使用 javascript
All you need is to make an ajax request to your pythoncode. You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
这篇关于从 JavaScript 代码调用 Python 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!