1. 程式人生 > >Django - Ajax - 使用裝飾器處理從前臺傳輸來的json格式資料

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')