本文介绍了从Javascript代码调用Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 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 part:

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中有一个易于编写的等价物

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)


推荐答案

您需要的是向您的pythoncode发出ajax请求。
你可以用jquery 来做到这一点,或使用只是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函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 19:03