简体   繁体   English

通过Django中的Ajax将JSON数据从视图传递到html

[英]Passing JSON data from views to html via ajax in Django

I cannot render html template with JSON data passed from views via ajax. 我无法使用通过Ajax从视图传递的JSON数据来呈现html模板。 I get correct JSON format from views and I can see the correct response in console.log(response) , but when I run from the browser this url http://127.0.0.1:8000/our-stores/ I get this result: 我从视图中获得了正确的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}]

But instead of this output I should get rendered ourstores.html file. 但是,除了此输出之外,我还应该渲染ourstores.html文件。 Please, find the code below: 请找到以下代码:

models.py 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 urls.py

urlpatterns = [
    url(r'^our-stores/$','shoppire.views.ourstores',name='ourstores'),
    url(r'^admin/', include(admin.site.urls)),
]

views.py 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 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 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'>&times;</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
    } 

    });

};

Thanks a lot! 非常感谢!

You do not render the ourstores.html template anywhere in your ourstores view. 您不会在ourstores视图中的任何位置呈现ourstores.html模板。 In order for a template to be displayed, it has to be rendered by the view. 为了显示模板,必须由视图呈现它。 In your case, if the request is AJAX, you'd want a JSON to be rendered and if the request is not AJAX, the actual template to be rendered. 在您的情况下,如果请求是AJAX,则需要呈现JSON;如果请求不是AJAX,则要呈现实际的模板。

Your view could look something like this: 您的视图可能如下所示:

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')

If you ask for JSON response, JSON response is what you will get. 如果您要求JSON响应,那么您将获得JSON响应。 If you want to render a template, use the following: 如果要渲染模板,请使用以下命令:

def ourstores(request): 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))

Then, inside your template use the passed data as {{response_data}} 然后,在模板内部,将传递的数据用作{{response_data}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM