How to pass variable from python to javascript
I have a server in python to handle id (youtube video id), this is the code:
class MessageHandler(tornado.web.RequestHandler):
def get(self, action_id):
print "Message = " + action_id
if action_id == "id":
for ws in opened_ws:
ws.write_message("ID: " + action_id)
return render_template('js/player.js', action_id=json.dumps(action_id))
(...)
I am using return render_template to pass "action_id" to player.js, which is a function to render movies using API from Youtube, code:
var PushPlayer = (function () {
var player = null;
function new_player() {
player = new YT.Player('yt-player', {
videoId: action_id,
}
});
}
(...)
Since action_id
I can have all youtube video IDs .. but I don't know who is transferring action_id
from python to javascript .. any idea?
Thank!
source to share
It looks like you are using Tornado. You can write Python source in the Tornado template . In this case, your player.js file is a Tornado template. You would like to update it like this:
var PushPlayer = (function () {
var player = null;
function new_player() {
player = new YT.Player('yt-player', {
videoId: {{ action_id }},
}
});
}
Anything inside the double curly braces will be evaluated as Python by Tornado.
source to share
If you are using a Python framework, you can access the value action_id
using a templating engine like Jinja2 (see http://flask.pocoo.org/docs/0.10/quickstart/#rendering-templates ).
Otherwise, to access action_id
with javascript, you can use an AJAX call, which is an asynchronous JavaScript request to your Python web server (see http://api.jquery.com/jquery.ajax/ ). Note that the call .ajax
is part of the jQuery library, but it can also be done without it.
source to share