javascriptpythonjson

How to send data from Python script to JavaScript and vice-versa?


I am trying to make a calculator (with matrix calculation also). I want to make interface in JavaScript and calculation stuff in Python. But I don't know how to send parameters from python to JavaScript and from JavaScript to python.

Edit: I want to send data via JSON (if possible).


Solution

  • In your javascript, you need to make a AJAX call to your server where your python is running. A package like axio will make things much easier:

    The following javascript will invoke the RESTAPI and perform according to the response

    var promise = axios.create({ baseURL: "https://yourhost/rootpath/", timeout: 100000 }).get("path/to/rest")
    promise.then((response) = > {... do something ...})
    

    On your Flask application, you define a function which is attached to your specified RESTApi Paht like this:

    @app.route('path/to/rest', methods=['GET'])
    def do_something():
        return {"result" : "value" }