2022暑期实践(Django教程学习记录)(第五周3)P57Ajax任务管理实例

本文展示了如何在Django框架下创建一个任务管理应用,结合Ajax技术进行异步数据交互。通过定义`TaskModelForm`表单类和相关视图函数,实现了任务的增删查改。在前端,使用jQuery的Ajax方法发送POST请求,处理表单数据,并展示反馈信息。同时,文章涵盖了错误处理和JSON响应的生成,以及前端错误信息的显示。
摘要由CSDN通过智能技术生成

(第五周3)P57Ajax任务管理实例

有较多涉及到JavaScript的知识,会套用就行
源代码:

class TaskModelForm(BootStrapModelForm):
    class Meta:
        model = models.Task
        fields = "__all__"
        widgets = {
            "detail": forms.Textarea,
        }


def task_list(request):
    form = TaskModelForm()
    return render(request, 'task_list.html', {'form': form})


from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def task_ajax(request):
    print(request.GET)
    print(request.POST)
    data_dict = {
        "status": True,
        "data": [11, 22, 33, 45],
    }
    # import json
    # json_string = json.dumps(data_dict)
    # return HttpResponse(json)
    # 可以利用django自带模块转成json格式
    from django.http import JsonResponse
    return JsonResponse(data_dict)


@csrf_exempt
def task_add(request):
    print(request.POST)
    import json
    # 基于ModelForm校验数据
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {
            "status": True,
        }
        json_string = json.dumps(data_dict)
        return HttpResponse(json_string)
    # else:
    print(type(form.errors))
    from django.forms.utils import ErrorDict
    # 可以直接用内部方法将错误信息转换成json
    data_dict = {
        "status": False,
        "error": form.errors,
    }
    json_string = json.dumps(data_dict, ensure_ascii=False)
    return HttpResponse(json_string)
{% extends 'layout.html' %}


{% block content %}
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">表单</div>
            <div class="panel-body">
                <form id="formAdd">
                    <div class="clearfix">
                        {% for field in form %}
                            <div class="col-xs-6">
                                <div class="form-group" style="position: relative; margin-bottom: 20px;">
                                    <label>
                                        {{ field.label }}
                                        <span style="color: red">{{ field.errors.0 }}</span>
                                    </label>

                                    {{ field }}
                                    <span  class="error_msg" style="color: red; position: absolute;"></span>
                                </div>
                            </div>
                        {% endfor %}
                        <div class="col-xs-12">
                            <button type="button" id="btnAdd" class="btn btn-default">提交</button>
                        </div>
                    </div>

                </form>
            </div>
        </div>

        <div>
            <hr/>
            <h1>Ajax案例</h1>

            <h3>示例1</h3>
            {#        <input type="button" class="btn btn-primary" value="点击" onclick="clickMe();"/>#}
            <input type="button" class="btn btn-primary" id="btn1" value="点击1"/>

            <h3>示例2</h3>
            <input type="text" id="nameUser" placeholder="姓名">
            <input type="text" id="ageUser" placeholder="年龄">
            <input type="button" class="btn btn-primary" id="btn2" value="点击2"/>

            <h3>示例3</h3>
            <form id="form3">
                <p><input type="text" name="user" placeholder="姓名"></p>
                <p><input type="text" name="age" placeholder="年龄"></p>
                <p><input type="text" name="email" placeholder="邮箱"></p>
                <p><input type="text" name="more" placeholder="年龄"></p>
                <p><input type="button" class="btn btn-primary" id="btn3" value="点击3"/></p>
            </form>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script type="text/javascript">
        {#基于dom方法绑定事件#}
        {#function clickMe(){#}
        {#    console.log("点击了按钮");#}
        {#    $.ajax({#}
        {#        url: '/task_ajax',#}
        {#type: 'get',#}
        {#        type: 'post',#}
        {#        data: {#}
        {#            n1: 123,#}
        {#            n2: 'abc',#}
        {#        },#}
        {#        success: function (res){#}
        {#            console.log(res);#}
        {#        }#}
        {#    })#}
        {# } #}

        $(function () {
            //页面框架加载完成后自动执行
            bindBtn1Event();
            bindBtn2Event();
            bindBtn3Event();

        })

        function bindBtn1Event() {
            $("#btn1").click(function () {
                $.ajax({
                    url: '/task_ajax/',
                    type: 'post',
                    data: {
                        n1: 123,
                        n2: 'abc',
                    },
                    {#将后端传过来JSON的转成字符串反序列化成JSON对象,使得前端可以直接调用#}
                    dataType: "JSON",
                    success: function (res) {
                        console.log(res);
                        console.log(res.data)
                    }
                })
            })
        }

        function bindBtn2Event() {
            $("#btn2").click(function () {
                $.ajax({
                    url: '/task_ajax/',
                    type: 'post',
                    data: {
                        name: $("#nameUser").val(),
                        age: $("#ageUser").val(),
                    },
                    {#将后端传过来JSON的转成字符串反序列化成JSON对象,使得前端可以直接调用#}
                    dataType: "JSON",
                    success: function (res) {
                        console.log(res);
                        console.log(res.data)
                    }
                })
            })
        }

        function bindBtn3Event() {
            $("#btn3").click(function () {
                $.ajax({
                    url: '/task_ajax/',
                    type: 'post',
                    {#示例3使用表单就不用一个个的传值了#}
                    data: $("#form3").serialize(),
                    {#将后端传过来JSON的转成字符串反序列化成JSON对象,使得前端可以直接调用#}
                    dataType: "JSON",
                    success: function (res) {
                        console.log(res);
                        console.log(res.data);
                    }
                })
            })
        }
    </script>
        <script type="text/javascript">
            $(function () {
                //页面框架加载完成后自动执行
                bindBtnAddEvent();

            })

            function bindBtnAddEvent() {
                $("#btnAdd").click(function () {
                    {#首先清空上一次的错误信息#}
                    $(".error_msg").empty();
                    $.ajax({
                        url: '/task_add/',
                        type: 'post',
                        {#示例3使用表单就不用一个个的传值了#}
                        data: $("#formAdd").serialize(),
                        {#将后端传过来JSON的转成字符串反序列化成JSON对象,使得前端可以直接调用#}
                        dataType: "JSON",
                        success: function (res) {
                            if (res.status) {
                                alter("添加成功");
                            } else {
                                console.log(res.error);
                                $.each(res.error, function (name, data){
                                    console.log(name, data);
                                    $("#id_"+name).next().text(data[0]);
                                })
                            }
                        }
                    })
                })
            }
        </script>
{% endblock %}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值