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, or use just javascript

  type: POST,
  url: ~/,
  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:

    function(data, textStatus, jqXHR) {

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:

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();, + text, true);
xhr.responseType = JSON;
xhr.onload = function(e) {
  var arrOfStrings = JSON.parse(xhr.response);

Leave a Reply

Your email address will not be published. Required fields are marked *