• 二 .python基于djago项目登录 ajax基本使用


    一. djago项目登录 ajax基本使用( ajax无页面刷新)

    https://download.csdn.net/download/baobao267/10722491   Django之Form表单验证及Ajax验证方式汇总

                    登录成功跳转>>>     

    models
    from django.db import models
    class UserInfo(models.Model):
    user=models.CharField(max_length=32)
    pwd=models.CharField(max_length=32)
    urls
    from django.contrib import admin
    from django.urls import path
    from app01 import views
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('index/', views.index),
        path('handle_ajax/', views.handle_ajax),
        path('cal/', views.cal),
        path('login/', views.login),
    ]
    viwes
    
    from django.shortcuts import render,HttpResponse
    # Create your views here.
    from app01.models import UserInfo
    import json
    
    def index(request):
        return render(request,"index.html")
    
    def handle_ajax(request):
        return HttpResponse("Ajax请求成功了哈哈哈")
    
    def cal(request):
        import time
        # time.sleep(10)
        # print(request.GET)
        # num1=request.GET.get("num1")
        # num2=request.GET.get("num2")
        num1=request.POST.get("num1")
        num2=request.POST.get("num2")
        ret=int(num1)+int(num2)
        return HttpResponse(str(ret))
    
    
    def login(reqeust):
        if reqeust.method=="POST":
            res={"user":None,"error":""}
            print(reqeust.POST)
            user=reqeust.POST.get("user")
            pwd=reqeust.POST.get("pwd")
            user_obj=UserInfo.objects.filter(user=user,pwd=pwd).first()
            if user_obj:
                res["user"]=user
            else:
                res["error"]="用户名或者密码错误!"
            return HttpResponse(json.dumps(res))
        else:
            return render(reqeust,"login.html")

    login.html 页面
    <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="/static/js/jquery-3.3.js"></script> </head> <body> <form> 用户名 <input type="text" id="user"> 密码 <input type="password" id="pwd"> <input type="button" value="提交" id="login_btn"><span class="error"></span> {% csrf_token %} </form> <script> $("#login_btn").click(function () { // 发送Ajax请求登录认证 $.ajax({ url:"/login/", type:"post", data:{ user:$("#user").val(), pwd:$("#pwd").val(), csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val() }, success:function (response) { console.log(response); // json字符串 var res=JSON.parse(response); console.log(res); if (res.user){ // 登陆成功 location.href="/index/" }else{ // 登录失败 $(".error").html(res.error).css("color","red"); setTimeout(function () { $(".error").html("") },1000) } } }) }) </script> </body> </html>
    index.html 页面
    
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="/static/js/jquery-3.3.js"></script>
    </head>
    <body>
    
    <h4>INDEX页面</h4>
    <button class="btn">提交Ajax</button>
    <p class="show"></p>
    <hr>
    {% csrf_token %}
    <input type="text" id="num1"> + <input id="num2" type="text"> = <input id="ret" type="text"><button class="cal">计算</button>
    
    <script>
    
           //   j简单的ajax请求
           $(".btn").click(function () {
    
               $.ajax({
                   url:"/handle_ajax/",
                   type:"get",
                   success:function (response) {
                       console.log(response);
                       $(".show").html(response)
                   }
               })
    
    
           });
    
           //  传参Ajax请求
           
           $(".cal").click(function () {
    
               var num1=$("#num1").val();
               var num2=$("#num2").val();
    
               $.ajax({
                   url:"/cal/",
                   type:"post",
                   data:{
                       num1:num1,
                       num2:num2,
                       csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val()
    
                   },
                   success:function (response) {
                       console.log(response);
                       $("#ret").val(response)
                   }
    
               })
    
    
           })
        
       
    </script>
    
    </body>
    </html>
    ajax发送数据格式知识点
    
    
    
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    
        <script>
    
            var i=10;
            var s='hello';
            var arr=["123",456,true];
            var obj={name:'alex',age:23};
    
            console.log(JSON.stringify(s));
            console.log(JSON.stringify(arr));
            console.log(JSON.stringify(obj));
    
          // console.log(JSON.parse(s));
          // console.log(JSON.parse(arr));
          console.log(JSON.parse('{"name":"alex","age":18}'))
            /*
            *     序列化方法:  JSON.stringify()  等同于Python json.dumps()
            *    反序列化方法: JSON.parse()      等同于Python json.loads()
            *
            *
            * */
            
    
        </script>
    </head>
    <body>
    
    </body>
    </html>
  • 相关阅读:
    Unable to load the specified metadata resource
    Web开发人员速查卡
    vs 中大括号之间垂直虚线显示
    第4届华为编程大赛决赛试题解答(棋盘覆盖)
    assert()函数用法总结
    Win7安装VC++6.0已知的兼容性问题的解决方法
    VC6打开一个文件或工程的时候,会导致VC6崩溃而关闭
    浮点数取整.
    1.4 VC6.0在win7下安装的兼容性问题以及解决办法
    华为编程大赛_将字符数组内的数字排序
  • 原文地址:https://www.cnblogs.com/lovershowtime/p/11484801.html
Copyright © 2020-2023  润新知