简体   繁体   中英

how can I pass parameter to javascript in flask and use it as image's src

I want to pass parameter to javascript and use it as image's src. But it doesn't work at all. when I hardcoded url, it worked. And this kind of url_for works at html too.

this is app.py

@app.route('/result')
def result_html():
 username = str(session['user'])
 url = 'images/'+username+'/test.jpg'
 return render_template('result.html',data = url)

and this is javascript function in html

  function checkImage(){
  var img = new Image();
  img.src = "{{ url_for('static', filename=data) }}"
  img.onload = function(){
      document.getElementById("changeImg").setAttribute("src","{{ url_for('static', filename=data) }}")
      document.getElementById("changeImg").setAttribute("style","padding-top: 5%; padding-bottom : 2%")
      document.getElementById("spinner-section").setAttribute("style","display:none");
      clearInterval(intervalId);
  }

This works:

Your view:

@app.route('/result')
def result_html():
    demoUrl = 'https://upload.wikimedia.org/wikipedia/en/d/d4/Mickey_Mouse.png'
    return render_template('result.html', url = demoUrl) 

Your template:

<img id="changeImg" >
<script>
    document.getElementById("changeImg").setAttribute("src","{{ url }}")
</script>

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