zoukankan      html  css  js  c++  java
  • Django_静态资源配置和ajax(九)

    一、静态资源配置

    静态资源的相关配置都在项目目录下的 settings.py 文件中进行配置。配置参数如下:

    # 浏览器访问静态资源时的路径
    STATIC_URL = '/static2/'
    # 存放静态资源的文件路径
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static'),
        os.path.join(BASE_DIR, 'booktest/static'),
    
    ]

     

     注意:django查找静态文件是惰性查找,查找到第一个,就停止查找了。

     二、AJAX

    什么是ajax?

    通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。也就说可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

    使用ajax

    下面以登录为例子介绍ajax在django中是如何使用的

    1、环境配置

    django使用ajax时需要先在上面创建的static文件目录下新建个js目录,然后将 jquery 这个js文件放在js目录下

     2、创建html模板文件

    在 templates 目录下创建 login.html文件,在文件中引入上面添加的js文件。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>ajax请求</title>
        <script src="/static/js/jquery-1.12.4.min.js"></script>
        <script>
            $(function(){
                // 在按钮上绑定click事件
                $("#sendAjax").click(function(){
                    // 获取输入框中的用户名和密码
                    var username = $('#username').val();
                    var password = $('#password').val();
    
                    // 使用ajax发送请求
                    $.ajax({
                        // 'url': '/booktest/login_ajax',
                        // 使用django去除url硬编码
                        'url': '{% url "booktest:login_ajax" %}',
                        'type': 'post',
                        'dataType': 'json',
                        'data': {
                            'username': username,
                            'password': password
                        }
                    }).success(function(data){      // 如果请求成功则执行,形参data为响应的数据
                        if( data.status_code==0 ){
                            alert('响应成功')
                        }else{
                            alert('响应错误')
                            return 
                        };
                        $('#message').html(data.data.message)
                        if( data.data.ret == 1){
                            $('#message').addClass('showColor')
                        }else{
                            $('#message').removeClass('showColor')
                            // 跳转到booktest首页
                            location.href = '/booktest/'
                        }
                    })
                });
            });
        </script>
        <style>
            .showColor{
                color: red;
            }
        </style>
    </head>
    <body>
        <div>用户名:<input type="text" name="username" id="username"></div>
        <div>密码:<input type="text" name="password" id="password"></div>  
        <div><input type="button" value="登录" id="sendAjax"></div>
        <div id="message"></div>
    </body>
    </html>

    3、编写视图函数并添加路由

    在views.py文件中编写视图函数,代码如下:

    from django.shortcuts import render
    from django.http import JsonResponse
    
    
    def login(request):
        """ 显示登录界面 """
        return render(request, "booktest/login.html")
    
    
    def login_ajax(request):
        """ 响应的数据 """
        # 获取POST请求参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'admin' and password == 'admin':
            data = {
                'status_code': 0,
                'data': {
                    'ret': 0,
                    'message': '登录成功'
                    }
                }
            # 注意:因为ajax是通过后台与服务器进行数据交换的,如果使用ajax调用的函数的响应数据是指向或重定向一个界面,浏览器是不会刷新界面的!只能通过前端实现界面跳转
            # return render(request, 'booktest/index.html')
        else:
            data = {
                'status_code': 0,
                'data': {
                    'ret': 1,
                    'message': '用户或密码错误'
                }
            }
        # 返回json格式数据
        return JsonResponse(data)

    在urls.py文件中配置路由:

    from django.urls import path
    from django.urls import re_path
    
    from booktest import views
    
    app_name = 'booktest'   # 增加命名空间
    urlpatterns = [
        path('login', views.login, name='login'),
        path('login_ajax', views.login_ajax, name='login_ajax'),
    ]

    4、运行django开发服务器进行验证

  • 相关阅读:
    PAT顶级 1024 Currency Exchange Centers (35分)(最小生成树)
    Codeforces 1282B2 K for the Price of One (Hard Version)
    1023 Have Fun with Numbers (20)
    1005 Spell It Right (20)
    1092 To Buy or Not to Buy (20)
    1118 Birds in Forest (25)
    1130 Infix Expression (25)
    1085 Perfect Sequence (25)
    1109 Group Photo (25)
    1073 Scientific Notation (20)
  • 原文地址:https://www.cnblogs.com/testlearn/p/13941730.html
Copyright © 2011-2022 走看看