Django - Ajax - 使用装饰器处理从前台传输来的json格式数据

目录

前端

视图层


前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>json</title>
    <script src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<body>
<form>
    <p>用户名:<input type="text" name="name" id="name"></p>

    <p>密码:<input type="password" name="pwd" id="pwd"></p>

    {#    <input type="submit" value="提交">#}

</form>

<button id="btn">ajax提交json格式</button>

</body>

</body>
<script>
    $('#btn').click(function () {

        var data_dic = {'name': $("#name").val(), 'pwd': $("#pwd").val()};
        var postr = JSON.stringify(data_dic);

        {#前台传输json格式数据#}
        $.ajax({
            url: 'app_1/json/',
            type: 'post',
            data: postr,
            contentType: 'application/json',
            dataType: 'json',
            success: function (data) {
                alert(data)
            }


        })
    })

</script>
</html>

视图层

from django.shortcuts import render, HttpResponse
import json


# Create your views here.

# ----直接截获request修改为解json格式数据返回给函数---------

def json_format(func):
    def inner(*args, **kwargs):
        # print('json_format:')
        # print(args)
        # print(args[0])

        if args[0].method == 'GET':
            # print('get')
            return render(args[0], 'json.html')

        data_dic = json.loads(args[0].body.decode('utf-8'))
        res = func(data_dic)
        return res
    return inner


@json_format
def json_web(request):
    # print(request)
    # print(type(request))
    return HttpResponse('ok')

# ----在request内增加data属性为解json格式属性---------

def json_format(func):
    def inner(request,*args, **kwargs):

        request.data = request.POST

        try:
            request.data = json.loads(request.body.decode('utf-8'))
        except Exception as e:
            print(e)

        res = func(request,*args, **kwargs)

        return res
    return inner

@json_format
def json_web(request):	
    if request.method == 'GET':
        print('get')
        return render(request, 'json.html')
    
    print(request.data)
    print(type(request.data))
    print(request.data.get('name'))

    return HttpResponse('ok')	

猜你喜欢

转载自blog.csdn.net/qq_33961117/article/details/84309489