【问题标题】:getting the value of python function from javascript从javascript获取python函数的值
【发布时间】:2017-04-14 16:24:36
【问题描述】:

我想知道是否有办法将 python 字典传递给 javascript?

好的,我正在使用bottle 来创建一个 Web 框架,我的设置是这样的:

runTheApp.py 我有:

# importing general packages
import bottle

@bottle.route('/')
def index():
  return bottle.template("index")

@bottle.route('/static/<filename>')
def server_static(filename):
  return bottle.static_file(filename, root="./js")

if __name__ == "__main__":
  bottle.run(host="localhost",port=8080,debug=True,reloader=True)

我想要访问的python字典在myData.py中:

def get_data(): 
    return {"Name":"James","City":"KL"}

我可以从 index.tpl 访问 python:

<!DOCTYPE html>
<html lang="en-us" xml:lang="en-us">
%import myData
%data = myData.get_data()
    <head>
    <title>Home</title>
    </head>
    <body>
    <p id="greeting"> Hi {{data["Name"]}} from {{data["City"]}} </p>
    </body>
    <script type="text/javascript" src="/static/changer.js"></script>
</html>

但我想从 changer.js 访问它,我有:

var greeting_p = document.getElementById("greeting");
var wishing_p = document.createTextNode("hope you are doign well.");
greeting_p.appendChild(wishing_p);

如何从 javascript 中获取 python 字典? 这样做是个好主意吗?比如它是安全的最佳实践吗?

【问题讨论】:

    标签: javascript html python-2.7 bottle


    【解决方案1】:

    您应该使用 AJAX 方法让瓶子应用程序以 JSON 格式(或 XML,如果您对此感到满意)返回数据,然后可以通过 JavaScript 函数操作返回的值。

    【讨论】:

    • 感谢回复,我想通了,瓶子里有个功能,调用模板时立即传字典,不用Ajax。
    • 但如果我想从 Javascript 调用它,Ajax 是解决方案。
    【解决方案2】:

    我想通了,下面是例子:

    像这样将字典传递给模板:

    @bottle.route('/')
    def index():
      data = [{"user":"Bernard"}]
      return bottle.template("index", data=data)
    

    在模板中就这样读吧:

    console.log("{{data['user']}}")
    

    另外,要像 Josh English 所说的那样从 javascript 中使用 Ajax 调用它,请创建一个 POST 函数并将字典作为 JSON 发送,如下所示:

    @bottle.route('/get-user-info', method="POST")
    def get_user_data():
        data = [{"user":"Bernard"}]
        retun json.dumps(data)
    

    然后像这样在 javascript 中调用 Ajax 来获取 JSON 文件:

    // getting the data
    var result = $.ajax({
            url: "/get-user-info",
            type: 'POST',
            dataType: 'json',
            contentType: "application/json",
            async: true,
    });
    

    希望对遇到同样问题的人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-10
      • 2012-04-21
      • 2016-01-07
      • 2021-02-18
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多