Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

javascript - Call python function from JS

I am trying to call a function in Python from my JavaScript code. I used the code explained here but it does not work for me.

Here is my JS code:

<!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 Code:

import csv
from numpy import genfromtxt
from numpy import matrix

def main():
    ...
    return x 
if __name__ == "__main__":
    x=main()
    return x;

Do you know what is wrong with it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Apart from the mentioned points and assuming you already have a proper setup to serve your python script and return the response. You should submit an asynchronous request, especially if the python code does some heavy computation.

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');

If you only do some light computation and you have no problem working with a code deprecated as of jQuery 1.8, go with the synchronous approach. This is not recommended as it blocks the main thread.

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);

Read more about it here: How do I return the response from an asynchronous call? and http://api.jquery.com/jquery.ajax/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...