簡體   English   中英

在Django中使用Ajax將數據從mysql傳遞到html

[英]Passing data from mysql to html using ajax in django

我使用ajax get方法將數據從views.py傳輸到html時get 我從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 %}

您是從視圖而不是HTML返回JSON,因此您不能簡單地將返回的JSON從jQuery傳遞給.html()方法,而期望它能自動將JSON呈現為HTML。

相反,您需要使用Underscore 模板之類的東西來呈現返回的對象數組中的每個項目。

另外,Django具有內置的JsonResponse ,因此您不必自己組成。

另外,您始終可以呈現HTML服務器端並將其傳遞回jQuery,但是根據返回的有效負載的大小,效率可能有所不同。

當DOM准備就緒時,我還將通過以下方式調用ShowStores()

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

而不是將其內聯到模板中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM