2015-08-29 249 views
8

我想從我的JavaScript代碼調用Python中的函數。我使用的代碼解釋here,但它不適合我。從JS調用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; 

你知道什麼是錯呢?

+1

'〜/ reverse_pca.py'是相對路徑,它看起來像它意味着是一個絕對路徑。無論如何,你應該提及任何錯誤信息(因爲「不工作」可能意味着很多事情),你應該觀看Web服務器日誌。 – betterworld

回答

7

除了提到的幾點,並假設你已經有一個適當的設置來爲你的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 and JS code -- 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 code -- 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)