简体   繁体   中英

Passing an url from python to JavaScript in Flask

I have this flask app

@app.route('', methods=['POST'])
def my_function():
 (...some functions...)
 map = some_url    
 return render_template ("main.html", map = map)

And I want to insert "map" into my JavaScript (.js is in /static):

 btn.addEventListener("click", function(){
   var newMap = document.createElement("IMG");     
   newMap.setAttribute("src", "{{map}}");
   newMap.setAttribute("width", "300");
   newMap.setAttribute("height", "300");

I do a print(map) before return render_template and it prints well but newMap is created but empty, like with no src .

There is an alternate solution which will work fine. You can create a hidden input and set its value to the map variable

<input type="hidden" value={{map}} id="inputId"/>

Now using javascript access the value and change setAtrribute second parmaeter to mapValue

mapValue = document.getElementById("inputId").value
newMap.setAttribute("src", mapValue);


                                

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM