简体   繁体   中英

Passing data from mysql to html using ajax in django

I have a problem to transfer data from views.py to html using ajax get method. I get correct json object from models.py in views.py, but javascript function ShowStores does not connect ourstores.html and views.py. I even do not see any output from ShowStores.js. Here is the code:

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

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

ShowStores.js

function ShowStores() {

console.log("show stores is working");

$.ajax({

    url : "ourstores/",
    type : "GET",
    dataType : "json",
    success: function(response){

        $("#show_stores").html(response);
        console.log(response);
        console.log("success");

    }

    }); 

};

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" align="center" onload="ShowStores()"></div>

 </div>

 {% endblock %}

You're returning JSON from the view, not HTML, so you can't simply pass the JSON returned to the .html() method from jQuery an expect it to automagically render the JSON to HTML.

Instead, you'll need to use something like Underscore's template to render each item in the array of objects returned.

Also, Django has a built-in JsonResponse , so you don't have to form up your own.

Alternatively, you can always render the HTML server-side and pass it back to jQuery, but depending on the size of the payload coming back, this may be more or less efficient.

I would also invoke ShowStores() when the DOM is ready via:

$(document).ready(function(){
    ShowStores();
});

instead of inlining it in your template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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