微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

一. djago项目登录 ajax基本使用( 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/",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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐