[英]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.