【问题标题】:Call python function from JS从 JS 调用 python 函数
【发布时间】:2015-08-29 17:15:27
【问题描述】:

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

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

你知道它有什么问题吗?

【问题讨论】:

  • ~/reverse_pca.py 是一个相对路径,看起来它应该是一个绝对路径。无论如何,您应该提及任何错误消息(因为“不起作用”可能意味着很多事情)并且您应该查看 Web 服务器日志。

标签: javascript python


【解决方案1】:

除了提到的几点,假设您已经有一个适当的设置来提供您的 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);

在此处了解更多信息:How do I return the response from an asynchronous call?http://api.jquery.com/jquery.ajax/

【讨论】:

【解决方案2】:

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

HTML 和 JS 代码:loging.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)

【讨论】:

  • 非常感谢!!这有帮助。
  • $ 未定义 error error 2
  • @henos jQuery 文件未加载。原始 URL 有错误。这部分“jquery 2.1.4”应该是带有连字符而不是空格的“jquery-2.1.4”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 2018-07-05
  • 2013-08-30
  • 1970-01-01
  • 2010-09-17
  • 1970-01-01
相关资源
最近更新 更多