Call Python function from JavaScript code

Call Python function from JavaScript code

All you need is to make an ajax request to your pythoncode.
You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript

$.ajax({
  type: POST,
  url: ~/pythoncode.py,
  data: { param: text}
}).done(function( o ) {
   // do something
});

From the document.getElementsByTagName I guess you are running the javascript in a browser.

The traditional way to expose functionality to javascript running in the browser is calling a remote URL using AJAX. The X in AJAX is for XML, but nowadays everybody uses JSON instead of XML.

For example, using jQuery you can do something like:

$.getJSON(http://example.com/your/webservice?param1=x&param2=y, 
    function(data, textStatus, jqXHR) {
        alert(data);
    }
)

You will need to implement a python webservice on the server side. For simple webservices I like to use Flask.

A typical implementation looks like:

@app.route(/your/webservice)
def my_webservice():
    return jsonify(result=some_function(**request.args)) 

You can run IronPython (kind of Python.Net) in the browser with silverlight, but I dont know if NLTK is available for IronPython.

Call Python function from JavaScript code

Typically you would accomplish this using an ajax request that looks like

var xhr = new XMLHttpRequest();
xhr.open(GET, pythoncode.py?text= + text, true);
xhr.responseType = JSON;
xhr.onload = function(e) {
  var arrOfStrings = JSON.parse(xhr.response);
}
xhr.send();

Leave a Reply

Your email address will not be published.