search

Home  >  Q&A  >  body text

Update 'div' after ajax request

<p>This is my first project in Django. I'm new to Django, ajax and javascript. I have to send data to jinja template after making ajax request. </p> <p>My index.html is as follows:</p> <pre class="brush:php;toolbar:false;">{% if data %} <p>{{data.title}}</p> <p>{{data.price}}</p> {% endif %}</pre> <p>My javascript is as follows:</p> <pre class="brush:php;toolbar:false;"><script> $.ajax({ type: "POST", url: "/", // Replace with the URL of the actual view data: { input_value: "test", csrfmiddlewaretoken: "{{ csrf_token }}" }, success: function(response) { title = response // After the request, the response will become { "data" : {"title":"t1", "price":20} } }, error: function() { console.log("Error") } }); <script></pre> <p>I don't know if this is possible. Some people use element.innerHTML to update, but I need to send to jinja format. Thank you</p>
P粉891237912P粉891237912483 days ago445

reply all(1)I'll reply

  • P粉403804844

    P粉4038048442023-08-18 10:45:59

    You have two options here, depending on your preference.

    1. Return a template instead of JSON The idea here is to generate the template on the server side and then return the generated HTML to the AJAX caller. So Ajax success is just appending this HTML fragment to the correct location.

    2. Render div in JS If you only have a JSON strategy or use DRF, the only way is to use a loop to loop through the received items and generate the equivalent HTML and then add it to the document.

    You can't put JinJa on the same page because when you generate the page to render it, you haven't received the data yet.

    reply
    0
  • Cancelreply