• Django与ajax、分页器


    ajax简单数据响应

    ajax请求,后台只需要返回信息,所以不会出现render、redirect

    模板层:

    $('.btn').click(function() {
        $.ajax({
            url: '/ajaxload/',  // 请求路径
            type: 'get|post',  // 请求方式
            data: {  // get和post都以data字典方式携带数据
                usr: 'abc',
                pwd: '123',
            },
            success: function(data) {
                // data为string类型数据
            },
            error: function(e) {
                // 请求失败分支
            }
        })
    })

    view层:

    def ajax_load(request):
        if request.is_ajax():
            if request.method == 'GET':
                usr = request.GET.get('usr', None)
                pwd = request.GET.get('pwd', None)
            if request.method == 'POST':
                usr = request.POST.get('usr', None)
                pwd = request.POST.get('pwd', None)
        return HttpResponse('OK')

    ajax对json数据响应

    模板层:

    $.ajax({
        ...,
        dataType: 'json',  // 如果用HttpResponse返回数据可能出现请求失败,尽量不要使用该方式
        data: {
            usr: $('.usr').val(),
            pwd: $('.pwd').val(),
        },
        success: function(data) {
            console.log(data)
            // data为object类型
        }
    })

    view层:

    def ajax(request):
        print(request.is_ajax())  # 是否是ajax请求
        if request.method == 'GET':  # 获取get请求数据
            usr = request.GET.get('usr', None)
            pwd = request.GET.get('pwd', None)
        if request.method == 'POST':  # 获取post请求数据
            usr = request.POST.get('usr', None)
            pwd = request.POST.get('pwd', None)
        
        # 返回字符串类型数据
        # return HttpResponse('OK')  # ***
    
        # 返回json类型数据
        dic = {'status': 'ok', 'msg': '登录成功'}
        data = json.dumps(dic, ensure_ascii=False)
        # 直接返回json模块处理后的json数据(json字符串),前台接收到的是一个json类型的字符串,需要前台自己处理
        # return HttpResponse(data)
        # 返回json字符串是,还告诉前台,该数据就是json类型字符串,设置响应头
        return HttpResponse(data, content_type='application/json')  # ****
        
        from django.http import JsonResponse
        # 返回json类型数据的终极方法
        dic = {'status': 'ok', 'msg': '登录成功'}
        return JsonResponse(dic, safe=False, json_dumps_params={'ensure_ascii': False})  # *****
        # 参数含义:
        # 返回值保证是字典类型
        # safe在False情况下就支持返回列表或字符串
        # 取消json的dumps方法采用的默认ascii编码中文

    分页器

    在页面显示分页数据,需要用到Django分页器组件

    from django.core.paginator import Paginator

    Paginator对象:    paginator = Paginator(user_list, 10)
    # per_page: 每页显示条目数量
    # count:    数据总个数
    # num_pages:总页数
    # page_range:总页数的索引范围,如: (1,10),(1,200)
    # page:     page对象    
    page对象:page=paginator.page(1)  # 具体第几页
    # has_next              是否有下一页
    # next_page_number      下一页页码
    # has_previous          是否有上一页
    # previous_page_number  上一页页码
    # object_list           分页之后的数据列表
    # number                当前页
    # paginator             paginator对象

    批量插入数据:

    book_list = []
    for i in range(100):
        book = Book(name='book%s' % i, price=11.11, publish_date='2018-1-1', publish_id=1)
        book_list.append(book)
    # 操作对象列表,一次操作多少条数据
    Book.objects.bulk_create(book_list, 20)

    模板层:

    <nav aria-label="Page navigation">
        <ul class="pagination">
            <li>
                {% if current_page.has_previous %}
                    <a href="/book/?page={{ current_num|add:-1 }}" aria-label="Previous">
                {% else %}
                    <a href="javascript:void(0)" aria-label="Previous">
                {% endif %}
                <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
            {% if current_num == 1 %}
                <li class="active">
                    {% else %}
                <li>
            {% endif %}
            <a href="/book/?page=1">1</a></li>
            <li><a href="javascript:void(0)">...</a></li>
            {% for num in page_range %}
                {% if current_num == num %}
                    <li class="active">
                        {% else %}
                    <li>
                {% endif %}
            <a href="/book/?page={{ num }}">{{ num }}</a></li>
            {% endfor %}
            <li><a href="javascript:void(0)">...</a></li>
    
            {% if current_num == num_pages %}
                <li class="active">
                    {% else %}
                <li>
            {% endif %}
            <a href="/book/?page={{ num_pages }}">{{ num_pages }}</a></li>
    
            <li>
                {% if current_page.has_next %}
                    <a href="/book/?page={{ current_num|add:1 }}" aria-label="Next">
                {% else %}
                    <a href="javascript:void(0)" aria-label="Next">
                {% endif %}
    
                <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        </ul>
    </nav>

    view层:

    def show_book(request):
        title = '图书详情'
        header = "图书管理系统"
        current_num = int(request.GET.get('page', 1))
        book_list = Book.objects.all()
        paginator = Paginator(book_list, 6)
        num_pages = paginator.num_pages
        if num_pages > 5:
            if current_num < 4:
                page_range = range(2, 5)
            elif current_num > paginator.num_pages - 3:
                page_range = range(num_pages - 3, num_pages)
            else:
                page_range = range(current_num - 1, current_num + 2)
        else:
            page_range = paginator.paginator
            
        current_page = paginator.page(current_num)
    
        return render(request, 'book.html', locals())
  • 相关阅读:
    nacos启动startup.cmd一闪而过
    阿里云轻量应用服务中的linux使用
    Mapper映射文件的文件头
    vue.js:634 [Vue warn]: Cannot find element: #app7
    使用idea连接数据库时报错 Server returns invalid timezone. Go to 'Advanced' tab and set 'serverTimezon
    调用本地摄像头进行拍照
    人人开源框架登录无验证码,控制台报错,验证码503 Service Unavailable
    报错:Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
    报错:com.alibaba.nacos.api.exception.NacosException: java.lang.reflect.Invocation
    报错Parameter 0 of method loadBalancerWebClientBuilderBeanPostProcessor in org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAuto
  • 原文地址:https://www.cnblogs.com/wangke0917/p/10512345.html
Copyright © 2020-2023  润新知