javascript - 从 JavaScript 代码调用 Python 函数

标签 javascript python function integration

我想从 JavaScript 代码调用 Python 函数,因为在 JavaScript 中没有替代方法可以做我想做的事。这可能吗?你能调整下面的代码片段来工作吗?

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)");

~/pythoncode.py 包含使用高级库的函数,这些函数在 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)

最佳答案

您只需要向您的 pythoncode 发出 ajax 请求。 您可以使用 jquery http://api.jquery.com/jQuery.ajax/ 执行此操作, 或者只使用 javascript

$.ajax({
  type: "POST",
  url: "~/pythoncode.py",
  data: { param: text}
}).done(function( o ) {
   // do something
});

关于javascript - 从 JavaScript 代码调用 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13175510/

相关文章:

python - 在plone中,使用collective.documentviewer,如果上传jpg或相应的pdf,占用的空间会更多吗?

C++:参数传递 "passed by reference"

javascript - 无法更新 angular.js 中的变量

javascript - 滚动后 Tippy 尺寸太大

python - Python 中的列表变得非常复杂

javascript - 如何将用户选择的酒店房间乘以入住天数?

Azure函数错误: microsoft. Azure.WebJobs.Extensions.Http

javascript - 每个(不同的)类触发一次点击事件

javascript - 为什么我们在 jquery 中使用 $(this)

python - 数字中的下划线是什么意思?