Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

339
Visualizações
How to give path of image from external JavaScript file in making Flask API?

I want to change the attribute value in the index.html file from the external JavaScript file linked to that HTML file.

I have folder structure as: folder structure

I can easily give path from html file using: {{url_for('static', filename='image_path')}}
But, this does not work while using in external JavaScript file.

     success: function (data) {
        var image_name = data["img_name"]
        var image_path = data["image_path"]

// I have image_path and image_name ready but could not find the exact method to use this...
// I want to use the image saved in "uploads" folder
        
        document.getElementById("uploadimg").setAttribute("src", {{url_for('uploads', filename='image_name')}});

      }

So, How can I use the absolute path or image_name to change the image in the frontend? Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

A common technique used by server-rendered pages is to create a JSON script thing in their HTML and query it from the (external) JS.

For example, in your Flask server, you'd so something like:

import json

# ...
@app.route("/page")
def page():
  data = json.dumps({
    "uploadImageUrl": url_for("uploads", filename="image_name")
    # you can include other data
  })
  return render_template("page.html", data=data)

Then stick this into your <head> tag:

<script type="application/json" id="data">{{ data }}</script>

Note that the browser only executes JavaScript when it is in a script with type text/javascript (default value if not specified), so when we add application/json, the browser will just leave our weird-smelling script tag alone.

In your external JavaScript you could do something like:

const data = JSON.parse(document.getElementById("data"));

// somewhere else in your code:
document.getElementById("uploadimg").setAttribute("src", data.uploadImageUrl);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda