Я не могу отобразить html-шаблон с данными JSON, переданными из представлений через ajax. Я получаю правильный формат JSON из представлений, и я могу видеть правильный ответ в console.log(response)
, но когда я запускаю из браузера этот URL http://127.0.0.1:8000/our-stores/
я получаю этот результат:
[{'fields': {'address': 'Kilpolantie 16',
'city': 'Helsinki',
'country': 'Finland',
'name': 'K-market'},
'model': 'shoppire.supermarket',
'pk': 1},
{'fields': {'address': 'Kontulankari 16',
'city': 'Helsinki',
'country': 'Finland',
'name': 'S-market'},
'model': 'shoppire.supermarket',
'pk': 2}]
Но вместо этого вывода я должен получить ourstores.html
файл. Пожалуйста, найдите код:
models.py
class Supermarket(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
country = models.CharField(max_length=50)
def __unicode__(self):
return self.name
urls.py
urlpatterns = [
url(r'^our-stores/$','shoppire.views.ourstores',name='ourstores'),
url(r'^admin/', include(admin.site.urls)),
]
views.py
def ourstores(request):
stores_list = Supermarket.objects.all()
response_data = serializers.serialize('json',stores_list)
return HttpResponse(response_data,content_type="application/json")
ourstores.html
{% extends 'base.html' %}
{% block content %}
<div class='col-sm-12' style='text-align:center'>
<h2>Check out our stores:</h2>
<div id="show_stores" onload="ShowStores()"></div>
<div id="results"></div>
</div>
{% endblock %}
ShowStores.js
$(document).ready(function(){
ShowStores();
});
function ShowStores() {
console.log("show stores is working");
$.ajax({
url : "our-stores",
type : "GET",
dataType : "json",
success: function(response){
$.each(response,function(index){
$('#results').append(response[index].fields.name);
console.log(response[index].fields.name);
});
console.log(response);
console.log("success");
},
error : function(xhr,errmsg,err) {
$('#show_stores').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
};
Большое спасибо!
Шаблон ourstores.html
не отображается в любом месте вашего ourstores
. Чтобы шаблон отображался, он должен отображаться в представлении. В вашем случае, если запрос является AJAX, вы хотите, чтобы JSON был визуализирован, и если запрос не является AJAX, фактический шаблон для визуализации.
Ваше мнение может выглядеть примерно так:
def ourstores(request):
if request.is_ajax():
stores_list = Supermarket.objects.all()
response_data = serializers.serialize('json',stores_list)
return HttpResponse(response_data,content_type="application/json")
return render(request, 'ourstores.html')
request.is_ajax()
имеет значение True
когда представление вызывается через AJAX.
Если вы попросите ответ JSON, ответ JSON - это то, что вы получите. Если вы хотите отобразить шаблон, используйте следующее:
def ourstores (запрос):
stores_list = Supermarket.objects.all()
response_data = serializers.serialize('json',stores_list)
return render_to_response('our_stores.html',
response_data,
context_instance=RequestContext(request))
Затем внутри шаблона используйте переданные данные как {{response_data}}