Django基础(9)_ajax请求

Ajax

jquery中each方法的使用

一  ajax的过程

  • views
# ajax解析
from django.http import HttpResponse

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        # 若想给前端返回一个字典类型的数据,需要使用json转换
        import json
        # 获取用户输入的用户名和密码在返回
        data = request.POST.dict()
        user_info = json.dumps(data, ensure_ascii=False)  # 加上ensure_ascii后转换的中文就不会转化成ascii字节码
        return HttpResponse(user_info)  # 返回给回调函数
  • html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax</title>
</head>
<body>
<h1>ajax登录验证</h1>
<label for="username">用户名</label>
<input type="text" id="username">

<label for="password">密码</label>
<input type="password" id="password">
<button id="btn">登录</button>

<h1 id="msg"></h1>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
$('#btn').click(function (){
$.ajax({
type:'post',
url:'/login/',
data:{
uname:$('#username').val(),
pwd:$('#password').val(),
},
success(data){
console.log(data, typeof(data)) // 但这里我们获取的字符串类型,所以还要使用parse转化为对象
var data_js = JSON.parse(data)
console.log(data_js,typeof(data_js))
// 然后我们就可以将用户名添加到h1标签中
$('#msg').text(data_js.uname)
},
error(){

}
})
})

</script>
</html>

大家发现没有上面的代码还需要我们自己进行序列化 ,那我们有没有办法解决这种情况呢

解决要反序列化的过程

其实在ajax请求到后台时,如果后代的响应头部中包含了: content-type:application\json,
那么到了前端ajax会看响应头键值对中有没有content-type(内容格式), 如果有并且值为application\json,那么ajax就会对响应的数据就行反序列化(不需要我们手动JSON.parse了),然后把数据传给对应的回调函数做参数

所以,我们只需要在后台响应的时候加上一个content-type:application\json的键值对,那么前端就不用在手动反序列化了

return HttpResponse(user_info, content_type='application\json')  # 返回给回调函数

这样我们前端获取的直接就是对象了

但是 这样我们每次响应的时候还得加上一个content_type是不是很麻烦, 所以Django给我们提供了一个JsonResponse

JsonResponse

from django.http import JsonResponse
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        data = request.POST.dict() 
        return JsonResponse(data)

我艹, 是不是感觉这样特别简单, 直接一个JsonResponse就解决了

下面来看一下正经的ajax请求

$.ajax({
    url: '',
    type: 'get',
    data:{     // 没有数据时data可以不写
        uname:'long',
        age: '18',
    },
    success:function(res){  //res是值当请求成功后,ajax的请求成功和失败由后台决定,如果后台响应的状态吗为2xx/3xx, 那么前端ajax获取到后,就知道请求成功了,就会自定触发success回调函数

    },
    error:function(error){ //相反,若后台返回的状态码为4xx/5xx的时候,就表示请求失败,就会自动触发error函数,响应结果就返回给error函数作为参数

    },
    
})

 

下面我们来测试一下ajax的两个函数: 

写一个登录验证,若登录成功就打印个ok,失败的话就提示个输入错误, 记得导入一下jquery

 

from django.shortcuts import render
from django.http import JsonResponse


def index(request):
    if request.method == 'GET':
        return render(request, 'index.html')
    else:
        print(request.POST)
        if request.POST.get('uname') == '王五':
            return JsonResponse('ok')
        else:
            error = '用户名或密码错误'

            return JsonResponse(error, safe=False, status=400)  # 响应非字典类型数据时,需要加上safe=False的参数

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>

</head>
<body>
    <h1>登录验证</h1>
    用户名:<input type="text" id="username">
    密码:<input type="password" id="password">
    <h4 id="error"></h4>
    <input type="submit" id="btn">
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $('#btn').click(function (){
        var uname = $('#username').val()
        var pwd = $('#password').val()
        $.ajax({
            url:'/index/',
            type:'post',
            data:{
                uname:uname,
                pwd:pwd,
            },success(res){
                {#console.log(res)#}
            },error(error){
                console.log(error)
                $('#error').text(error.responseJSON)   # 不知道用什么的时候就console.log()在控制台看一下
            }
        })
    })

</script>

</html>

 

 实时验证用户输入的长度

def food(request):
    if request.method == 'GET':
        return render(request, 'food.html')
    else:
        length = request.POST.get('len')
        if len(length) > 10:
            msg = '太长了'
            return HttpResponse(msg)
        else:
            return HttpResponse(len(length))

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>food</title>
    <!--实时监控用户输入的长度-->
</head>
<body>
    <h2>小伙子,你的长度是</h2>
    <input type="text" id="len">
    你的长度为:<span id="show"></span>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
    $("[type='text']").on('input',function (){
        // 把输入的长度传给后端
        $.ajax({
            url:'/food/',
            type:'post',
            data:{len:$('#len').val()},
            success(res){
                console.log(res)
                $('#show').text(res)
            }
        })
    })
</script>
</html>

 后端传入前端列表展示

 

 

 

  •  views
def food_list(request):
    if request.method == 'GET':
        return render(request, 'food_list.html')


def food_show(request):
    food_list = ['黄瓜', '茄子', '香蕉', '萝卜', '冬瓜']
    return JsonResponse(food_list, safe=False)

 

  •  food_list
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>fivenian</title>
    <!--后端传过来个列表前端展示-->
</head>
<body>
    <div>
        <strong>你的最爱</strong>
        <button id="btn">点我</button>
        <ul id="food_ul">

        </ul>
    </div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $('#btn').click(function (){
    $.ajax({
        url:'/food_show/',  
        type:'get',
        success(res){
            console.log(res)
            var ulEle = $('#food_ul'); 
            $.each(res,function (k,v){   // jquery中的each方法,使DOM循环结构简洁,
                // k是列表的索引
                // v是列表的元素
                var newLiEle = document.createElement('li');
                newLiEle.innerText = v;
                ulEle.append(newLiEle);
            })
        }
    })
 })
</script>
</html>

 

posted @ 2020-12-01 21:50  死里学  阅读(1)  评论(0)    收藏  举报