How to pass variable from python to javascript

本小妞迷上赌 提交于 2019-12-02 18:28:03

问题


I have a server in python to process an id (the id of youtube video), 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 use the return render_template to pass "action_id" to player.js, which is a function to process films using the API from Youtube, the code is :

var PushPlayer = (function () {

    var player = null;

    function new_player() {
        player = new YT.Player('yt-player', {
            videoId: action_id,
            }
        });
    }

(...)

With action_id, i can have everything id of youtube's video.. but i don't know who pass the action_id from python to javascript..any idea?

Thanks!


回答1:


It looks like you're using Tornado. You can write raw Python in a Tornado template. Your player.js file is a Tornado template in this case. You would want to update it like this:

var PushPlayer = (function () {

var player = null;

function new_player() {
    player = new YT.Player('yt-player', {
        videoId: {{ action_id }},
        }
    });
}

Anthing inside the double curly braces will be evaluated as Python by Tornado.




回答2:


If you are using a Python framework like Flask, you can access the value of action_id using a template engine like Jinja2 (see http://flask.pocoo.org/docs/0.10/quickstart/#rendering-templates).

Otherwise, to access the action_id using 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 .ajax call is part of the JQuery library, but this can also be done without it.



来源:https://stackoverflow.com/questions/27307563/how-to-pass-variable-from-python-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!