Django ajax 局部加载、异步刷新

Django ajax 局部加载、异步刷新

ajax 异步加载视图函数

# 展示分类页面,post 时进行 ajax 提交
from django.http import HttpResponse
from django.core import serializers   # 进行序列化返回页面

def show_cate(request):
    cate = Cate.objects.all()
    if request.method == 'POST':
        id = request.POST.get('id')  # 获取到分类的 ID

        cate = Cate.objects.filter(id=id).first()   # 根据 ID 查找分类数据
        computer = Computer.objects.filter(cate=cate).all()   # 查找分类下的所有电脑信息

        computer = serializers.serialize('json',computer,ensure_ascii=False)
        return HttpResponse(computer)

    return render(request,'show_cate.html',locals())

ajax 异步加载页面

# show_cate.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>分类展示页面</title>
    <script src="/static/js/jquery-1.10.2.min.js"></script>
    <script src="/static/js/jquery.cookie.js"></script>
</head>
<body>
    <a href="/">点击返回首页</a><br><br>
    <hr>
    {% for i in cate %}
    <button id="{{i.id}}">{{i.name}}</button>&nbsp;&nbsp;&nbsp;&nbsp;
    {% endfor %}
    <br><br>
    <div id="content"></div>
</body>

<script>
    $(document).ready(function(){
        $('button').click(function(){
            var id = this.id
            //console.log(id)
            
            $.ajax({
                url:'/show_cate/',
                type:'post',
                data:{
                    'csrfmiddlewaretoken': $.cookie('csrftoken'),
                    id:id
                },
                success:function(res){
                    var res = JSON.parse(res)
                    //console.log(res)
                    var html = ''
                    for (var i=0;i<res.length;i++){
                        html += "
  • "+res[i]['fields']['name']+"

  • "
    } $('#content').html(html) } }) }) }) </script> </html>

    你可能感兴趣的:(Django)