I'm wondering if there is a way to pass a python dictionary to javascript?
okay, I'm using bottle to have a web framework and my setup is something like this:
enter image description here
in runTheApp.py I have:
# 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)
and my python dictionary that I want to access from is in myData.py:
def get_data():
return {"Name":"James","City":"KL"}
I can access to python from index.tpl:
<!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>
but I want to access to it from changer.js, in there I have:
var greeting_p = document.getElementById("greeting");
var wishing_p = document.createTextNode("hope you are doign well.");
greeting_p.appendChild(wishing_p);
How can I get the python dictionary from javascript? is it a good idea doing this? as in is it secure and best practice?
2 Answers 2
You should use an AJAX method to let the bottle app return the data in JSON format (or XML, if you're comfortable with that) and the returned value can then be manipulated by the JavaScript function.
I figure that out, here is the example:
Passing dictionary to the template like so:
@bottle.route('/')
def index():
data = [{"user":"Bernard"}]
return bottle.template("index", data=data)
and in the template just read it like so:
console.log("{{data['user']}}")
also, to call it with Ajax from javascript like what Josh English said, make a POST function and send the dictionary as JSON like so:
@bottle.route('/get-user-info', method="POST")
def get_user_data():
data = [{"user":"Bernard"}]
retun json.dumps(data)
And call Ajax in javascript like so to get the JSON file:
// getting the data
var result = $.ajax({
url: "/get-user-info",
type: 'POST',
dataType: 'json',
contentType: "application/json",
async: true,
});
Hope that help anyone that has the same problem.