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?
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.