从JS调用python函数

Bah*_*ket 11 javascript python

我试图从我的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);
});
Run Code Online (Sandbox Code Playgroud)

Python代码:

import csv
from numpy import genfromtxt
from numpy import matrix

def main():
    ...
    return x 
if __name__ == "__main__":
    x=main()
    return x;
Run Code Online (Sandbox Code Playgroud)

你知道它有什么问题吗?

Far*_*d T 13

除了提到的要点之外,假设您已经有适当的设置来提供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');
Run Code Online (Sandbox Code Playgroud)

如果您只进行一些轻量级计算,并且在使用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);
Run Code Online (Sandbox Code Playgroud)

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


Bah*_*ket 6

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

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>
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)