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

196
Visualizações
Agregar múltiples parámetros a un script JS desde HTML

Me gustaría pasar algunos datos de mi función de vista de Python a un script JS usando HTML. Esa es mi función de vista

 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})

Mi formulario contiene cuatro parámetros, uno de ellos se llama iterations y ese es el que me gustaría pasar al script JS. Además, me gustaría pasar start_grid .

Traté de hacerlo de la siguiente manera en mi archivo HTML

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

Luego, en mi script JS escribí

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

Funcionó perfectamente, imprimí la grilla en mi consola. Similar podría tomar iterations de HTML

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

Cuando traté de agregar ambas variables en mi script JS, no funcionó.

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

¿Cómo puedo pasar varias variables a mi script JS? ¿Cuál sería la mejor manera de hacerlo?

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

0

Lo mejor es usar alguna combinación de ajax y ver funciones, si aprende este patrón, puede lograr mucho:

vistas.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 ... } }); }

Una vez que comprenda esto, podrá pasar datos sin problemas entre el frontend y el backend. Déjeme saber si usted necesita más detalles.

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