I'd like to call a Python function from JavaScript code, because there isn't an alternative in JavaScript for doing what I want. Is this possible? Could you adjust the below snippet to work?
JavaScript code:
var tag = document.getElementsByTagName("p")[0]; text = tag.innerHTML; // Here I would like to call the Python interpreter with Python function arrOfStrings = openSomehowPythonInterpreter("~/pythoncode.py", "processParagraph(text)");
~/pythoncode.py
contains functions using advanced libraries that don't have an easy to write equivalent in JavaScript:
import nltk # is not in JavaScript def processParagraph(text): ... nltk calls ... return lst # returns a list of strings (will be converted to JavaScript array)
Use ajax to Call Python From JavaScript. AJAX stands for Asynchronous JavaScript and XML. It utilizes the XMLHttpRequest object to communicate with servers. It can send and receive information in numerous formats, including HTML, XML, JSON, and text files.
You've seen how to connect JavaScript to Python and send data to the server, but that's only a scratch of the surface. You can dig deeper by connecting the Flask REST API to a database like MongoDB—so this lets you have a repository to store the posted data.
Using ajax, send text to a python script on your server. Set up the script to return data in an easy to parse (for js) notation (like JSON) and assign the result to arrOfStrings in the success handler. You can run the official Python interpreter in the browser by compiling it using clang and Emscripten.
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¶m2=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 don't know if NLTK is available for IronPython.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With