从JS调用python函数 [英] Call python function from JS

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

问题描述

我试图从我的JavaScript代码中调用Python中的函数。我使用了此处解释的代码,但它对我不起作用。

I am trying to call a function in Python from my JavaScript code. I used the code explained here but it does not work for me.

这是我的JS代码:

<!DOCTYPE html>
<body>
<script type="text/javascript" src="d3/d3.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>  
<script>
text ="xx";

$.ajax({
type: "POST",
url: "~/reverse_pca.py",
data: { param: text}
}).done(function(o) {
    console.log(data);
    console.log(text);
});

Python代码:

import csv
from numpy import genfromtxt
from numpy import matrix

def main():
    ...
    return x 
if __name__ == "__main__":
    x=main()
    return x;

你知道它有什么问题吗?

Do you know what is wrong with it?

推荐答案

除了上述要点之外,假设您已经有适当的设置来提供python脚本并返回响应。你应该提交一个异步请求,特别是如果python代码做了一些繁重的计算。

Apart from the mentioned points and assuming you already have a proper setup to serve your python script and return the response. You should submit an asynchronous request, especially if the python code does some heavy computation.

function postData(input) {
    $.ajax({
        type: "POST",
        url: "/reverse_pca.py",
        data: { param: input },
        success: callbackFunc
    });
}

function callbackFunc(response) {
    // do something with the response
    console.log(response);
}

postData('data to process');

如果您只进行一些轻量级计算,并且从jQuery 1.8开始不使用代码就没有问题,采用同步方法。这是不推荐,因为它会阻止主线程。

If you only do some light computation and you have no problem working with a code deprecated as of jQuery 1.8, go with the synchronous approach. This is not recommended as it blocks the main thread.

function runPyScript(input){
    var jqXHR = $.ajax({
        type: "POST",
        url: "/reverse_pca.py",
        async: false,
        data: { param: input }
    });

    return jqXHR.responseText;
}

// do something with the response
response= runPyScript('data to process');
console.log(response);

在此处阅读更多相关信息:如何从异步调用中返回响应? http://api.jquery.com/jquery.ajax/

Read more about it here: How do I return the response from an asynchronous call? and http://api.jquery.com/jquery.ajax/

这篇关于从JS调用python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆