python django初识ajax

什么是json

json是轻量级文本数据交互格式

json独立语言

符合的json对象

["one", "two", "three"]
{ "one": 1, "two": 2, "three": 3 }
{"names": ["张三", "李四"] }
[ { "name": "张三"}, {"name": "李四"} ]

不合格的json对象

{ name: "张三", 'age': 32 }  // 属性名必须使用双引号
[32, 64, 128, 0xFFF] // 不能使用十六进制值
{ "name": "张三", "age": undefined }  // 不能使用undefined
{ "name": "张三",
  "birthday": new Date('Fri, 26 Aug 2011 07:13:10 GMT'),
  "getName":  function() {return this.name;}  // 不能使用函数和日期对象
}

json支持的7种数据格式

Python JSON
dict object
list, tuple array
str, unicode string
int, long, float number
True true
False false
None null

javaScript中关于json对象和字符串转换的2种方法

JSON.parse(): 用于将一个 JSON 字符串转换为 JavaScript 对象

JSON.parse('{"name":"Q1mi"}');
JSON.parse('{name:"Q1mi"}') ;   // 错误
JSON.parse('[18,undefined]') ;   // 错误

JSON.stringify(): 用于将 JavaScript 值转换为 JSON 字符串

JSON.stringify({"name":"Q1mi"})

Ajax简介

  • 同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
  • 异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。

除了异步特点外,还有一个就是浏览器页面局部刷新

发请求给服务器的途径

1. 地址栏:get
2. form表单,支持get和post
3. 超链接 <a href="/path/">click</a> 这种是get方式
4. Ajax请求: 可以指定get和post

发Ajax请求一般返回httpResponse()

from django.shortcuts import render, HttpResponse
from app01 import models
import json
from django.http import JsonResponse

def index(request):
    return render(request, 'index.html')

def login(request):
    user = request.POST.get("user")
    pwd = request.POST.get("pwd")
    #根据表单的用户名和密码到数据库中匹配
    user_obj = models.User.objects.filter(username=user, password=pwd).first()
    print(user_obj)
    #一般请求下,需要定义一个字典。msg是约定成俗的名字,用来做提示的
    response = {"user":None,"msg":None}
    if user_obj:  # 判断有返回结果的请求下
        response["user"] = user_obj.username  # 修改字典的用户名
        print(user_obj.username)
    else:
        response["msg"] = "用户名或者密码不一致"  # 修改提示信息
    #返回json格式数据,默认序列化时,对中文默认使用的ascii编码。
    # ensure_ascii=False表示显示真正的中文
    # return HttpResponse(json.dumps(response, ensure_ascii=False))
    return JsonResponse(response)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <style type="text/css">
        input {
            width: 50px;
        }
    </style>
</head>
<body>
{% csrf_token %}
<h4>登录验证</h4>
<form>
    <lable>用户名</lable>
    <input type="text" id="user">
    <lable>密码</lable>
    <input type="password" id="pwd">
    <input type="button" value="提交" id="login_btn">
    {#显示错误信息#}
    <span class="error"></span>
</form>
{% csrf_token %}
<script>
    $("#login_btn").click(function () {
        var csrf = $("[name=csrfmiddlewaretoken]").val();
        //发送ajax请求
        $.ajax({
            url: "/login/",  //请求的url
            type: "post", //默认get
            data: {
                user: $("#user").val(),
                pwd: $("#pwd").val(),
                csrfmiddlewaretoken: csrf,
            },
            success: function (data) {  //data接收响应体,必须要有
                console.log(data);  //打印响应体
                console.log(typeof data);  //打印数据类型
                {#var data = JSON.parse(data);  //反序列化数据#}

                if (data.user) { // 登陆成功
                    //window.location.href表示跳转页面
                    alert("登录成功");
                    window.location.href = "/index/";
                } else {  // 登陆失败
                    //修改span标签,显示失败的返回值,并显示红色,左间距20px
                    $(".error").text(data.msg).css({"color": "red", "margin-left": "20px"})
                    //设置定时器,2秒后清空提示信息
                    setTimeout(function () {
                        $(".error").text("")  //清空提示信息
                    }, 2000)
                }
            }
        })
    });
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/zaizai1573/p/10480352.html