简体   繁体   English

在Django中使用Ajax将数据从mysql传递到html

[英]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. 我使用ajax get方法将数据从views.py传输到html时get I get correct json object from models.py in views.py, but javascript function ShowStores does not connect ourstores.html and views.py. 我从views.py中的models.py获取了正确的json对象,但是javascript函数ShowStores无法连接ourstores.html和views.py。 I even do not see any output from ShowStores.js. 我什至看不到ShowStores.js的任何输出。 Here is the code: 这是代码:

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

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

ShowStores.js 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 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. 您是从视图而不是HTML返回JSON,因此您不能简单地将返回的JSON从jQuery传递给.html()方法,而期望它能自动将JSON呈现为HTML。

Instead, you'll need to use something like Underscore's template to render each item in the array of objects returned. 相反,您需要使用Underscore 模板之类的东西来呈现返回的对象数组中的每个项目。

Also, Django has a built-in JsonResponse , so you don't have to form up your own. 另外,Django具有内置的JsonResponse ,因此您不必自己组成。

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. 另外,您始终可以呈现HTML服务器端并将其传递回jQuery,但是根据返回的有效负载的大小,效率可能有所不同。

I would also invoke ShowStores() when the DOM is ready via: 当DOM准备就绪时,我还将通过以下方式调用ShowStores()

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

instead of inlining it in your template. 而不是将其内联到模板中。

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

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