Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda