Я отправил Ajax запрос на сервер, чтобы получить отфильтрованные данные, и вот образец, который я получаю от сервера:
(3) [{…}, {…}, {…}]
0: {id: 1, title: "12 Rue Longueil", slug: "12-rue-longueil", latitude: null, longitude: null, …}
1: {id: 2, title: "15 Rue Sherbrooke LM", slug: "15-rue-sherbrooke-lm", latitude: null, longitude: null, …}
2: {id: 3, title: "Cycle Neron", slug: "cycle-neron", latitude: "-73.5987000000000000", longitude: "45.4799000000000000", …}
length: 3
__proto__: Array(0)
данные, указанные выше, регистрируются с консоли.
I хотите отображать эти данные в тегах HTMl на картах ниже.
but for that I need to use that received data and create children using JavaScript e.g. document.createElement('DIV')
. and then place these data.
$(document).on('submit', "#filterform", function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: "{% url 'listing:search' %}",
data: {
listing_for: $('#listing_for').val(),
// cutted
},
success: function (response) {
const listings = eval(response);
const content = document.getElementById('content');
for (let i = 0; i < listings.length; i++) {
const div = document.createElement('div');
div.className = 'listing mgb-1';
div.innerHTML = data[i].title;
content.appendChild(div);
// have to create, add lots of divs and classes
}
}
})
})
I was wondering if there is a way to sent Ajax request data as template variable? Or do I have to hardcode all HTML tags using Javascript?
Edit: Edited content based on first answer creating a separate HTML.
def search(request):
...
lst = list()
for listing in queryset:
ser = ListingSerializer(listing)
lst.append(ser.data)
return render(request, 'listing/newHtmlFile.html', {'listings': json.dumps(lst)})
separate HTML:
{% for list in listings %}
{{list.title}} {% endfor%}
и ajax запрос:
success: function (response) {
document.querySelector('#content').insertAdjacentHTML('beforeend', response);
}