在django中使用ajax将数据从mysql传递到html

Passing data from mysql to html using ajax in django

本文关键字:mysql html 数据 django ajax      更新时间:2023-09-26

我有一个使用ajax get方法将数据从views.py传输到html的问题。我在views.py中从models.py中获得正确的json对象,但javascript函数ShowStores没有连接ourstores.html和views.py。我甚至没有看到ShowStores.js的任何输出。下面是代码:

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 %}

你从视图返回JSON,而不是HTML,所以你不能简单地传递JSON返回到.html()方法从jQuery并期望它自动渲染JSON到HTML。

相反,您需要使用类似Underscore模板的东西来呈现返回的对象数组中的每个项。

此外,Django有一个内置的JsonResponse,所以你不必自己创建。

或者,您可以始终呈现HTML服务器端并将其传递回jQuery,但这取决于返回的有效负载的大小,这可能或多或少有效。

当DOM准备好时,我也会调用ShowStores():

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