从JS调用python函数

时间:2015-08-29 17:15:28

标签: javascript python

我试图从我的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;

你知道它有什么问题吗?

2 个答案:

答案 0 :(得分: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');

如果您只进行一些轻量级计算,并且在使用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/

答案 1 :(得分:5)

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

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)