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

189
Visualizações
Adding multiple parameters to a JS script from HTML

I would like to pass some data from my Python view function to a JS script using HTML. That's my view function

def home(request):
    if request.method == 'POST':
        params = GameOfLifeForm(request.POST)
        if params.is_valid():
            starting_grid = get_starting_grid(params.cleaned_data)
            to_html = {
                'animation': True,
                'gameoflifeform': params,
                'start_grid': starting_grid,
            }
        else:
            to_html = {
                'animation': False,
                'warning_msg': 'Something went wrong. Try once again.'
            }
        return render(request, 'get_animations/home.html', to_html)
    else:
        form = GameOfLifeForm()
        return render(request, 'get_animations/home.html', {'gameoflifeform': form})

My form contains four parameters, one of them is called iterations and that is the one I would like to pass to JS script. Moreover I would like to pass start_grid.

I tried to do it in the following way in my HTML file

{{ start_grid | json_script:"start-grid" }}
<script
  type="text/javascript"
  src="{% static 'js/runGameOfLife.js' %}"
></script>

Then in my JS script I wrote

var startGrid = JSON.parse(document.getElementById("start-grid").textContent);
console.log(startGrid);

Worked perfectly, I got the grid printed out in my console. Similar I could grab iterations from HTML

{{ gameoflifeform.iterations.value | json_script:"iterations"}}
<script
  type="text/javascript"
  src="{% static 'js/runGameOfLife.js' %}"
></script>

When I tried to add both variables into my JS script it didn't work.

{{ gameoflifeform.iterations.value | json_script:"iterations"}}
{{ start_grid | json_script:"start-grid" }}
<script
  type="text/javascript"
  src="{% static 'js/runGameOfLife.js' %}"
></script>

How can I pass several variables into my JS script? What would be the best way of doing it?

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

0

Best to use some combination of ajax and view functions, if you learn this pattern you can accomplish a lot:

views.py

def my_view_function(request):

    ''' this method accepts data from the front end, 
        processes it, and returns a response '''

    # unpack post request:
    first_value = request.POST.get('first_key')

    # do some logic:
    ...

    # pack response
    response = {
        "second_key" : "second_value"
    }

    # return a json response:
    return JsonResponse(response)

scripts.js

function post_request() {

  /* set an event to trigger this method
     this method will then send data to the backend
     and process the response */

  // send an ajax post request:
  $.ajax({
    type : 'POST',
    url : 'the_url',
    data : {
      first_key : 'first_value'
    },
    success : function(response) {
 
      // unpack response
      second_value = response.second_key

      // do some logic
      ...
    }
  });

}

Once you understand this, you will be able to seamlessly pass data back and forth between the frontend and backend. Let me know if you need more details.

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