从 JS 调用 python 函数

IT技术 javascript python
2021-03-12 13:48:51

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

这是我的 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;

你知道它有什么问题吗?

2个回答

除了提到的几点,并假设你已经有一个合适的设置来为你的 python 脚本提供服务并返回响应。您应该提交一个异步请求,尤其是当 Python 代码进行一些繁重的计算时。

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 起已弃用的代码没有问题,请使用同步方法。不建议,因为它阻止主线程。

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/

我得到 '$' 未定义。请帮忙。
2021-04-16 13:48:51
@SubtleCoder 你需要导入 jQuery;w3schools.com/jquery/jquery_get_started.asp
2021-04-28 13:48:51
非常感谢!
2021-05-16 13:48:51

经过几个小时的搜索,我最终得到了以下内容,并且效果很好。希望这有助于将来的其他人。

HTML 和 JS 代码:logging.html

<html>
 <head>
    <title>Flask Intro - login page</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="static/bootstrap.min.css" rel="stylesheet" media="screen">
    <script type="text/javascript" src="http://code.jquery.com/jquery 2.1.4.min.js"></script>  
 </head>
 <body>
    <input id="submitbutton" type="submit" value="Test Send Data">
    <!----------------------------------->
    <script type="text/javascript">

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

        return jqXHR.responseText;
    }

    $('#submitbutton').click(function(){
        datatosend = 'this is my matrix';
        result = runPyScript(datatosend);
        console.log('Got back ' + result);
    });

</script>

Python 代码:app.py

from flask import Flask, render_template, redirect, url_for,request
from flask import make_response
app = Flask(__name__)

@app.route("/")
def home():
    return "hi"
@app.route("/index")

@app.route('/login', methods=['GET', 'POST'])
def login():
   message = None
   if request.method == 'POST':
        datafromjs = request.form['mydata']
        result = "return this"
        resp = make_response('{"response": '+result+'}')
        resp.headers['Content-Type'] = "application/json"
        return resp
        return render_template('login.html', message='')

if __name__ == "__main__":
    app.run(debug = True)

非常感谢!!这有帮助。
2021-04-20 13:48:51
$未定义 错误 错误2
2021-04-20 13:48:51
@henos jQuery 文件未加载。原始 URL 有错误。这部分“jquery 2.1.4”应该是“jquery-2.1.4”,带连字符而不是空格。
2021-05-04 13:48:51