Django Ajax调用

Ajax

class Getcate(View):
def get(self,request):
cate=Cate.objects.all()
return render(request,'com/getcate.html',locals())
def post(self,request):
mes={}
cid=request.POST.get('cid')
print(cid)
computer=Computer.objects.filter(cate=cid).all()
print(computer)
computerlist=[]
for i in computer:
computerlist.append(i.to_dict())
mes['code']=200
mes['computerlist']=computerlist
return HttpResponse(json.dumps(mes))


需要引入css/js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="/static/admin/js/jquery-1.12.4.min.js"></script>
</head>
<body>
<ul>
{% for i in cate %}
<button><a href="javascript:addcomputer({{ i.id }})">{{ i.name }}</a></button>
{% endfor %}
</ul>

<div class="clist"></div>
</body>
<script type="text/javascript">
function addcomputer(id){
$.ajax({
url:'/com/getcate/',
type:'post',
data:{'cid':id},
dataType:'json',
success:function(res){
if(res.code==200){
var mes=res.computerlist
var len=mes.length
var html='<table border=2>'
html+='<tr><td>名称</td><td>价格</td><td>图片</td><td>显示器</td><td>处理器</td></tr>'
for (var i=0;i<len;i++){
html+='<tr><td>'+mes[i]['name']+'</td><td>'+mes[i]['price']+'</td><td><img src='+mes[i]['img']+'></td><td>'+mes[i]['xsq']+'</td><td>'+mes[i]['cpu']+'</td></tr>'
}
}
html+='</table>'
$('.clist').html(html)
}
})
}

</script>
</html>

上一篇:PDF上的内容无法复制粘贴


下一篇:keil (MDK + C51) 安装教程