Update 'div' after ajax request
P粉891237912
2023-08-17 11:47:33
<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>
You have two options here, depending on your preference.
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.
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.