【web开发】9、Django(4)ajax请求

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 一、Ajax是什么?
  • 二、使用步骤
  • 二、订单管理


提示:以下是本篇文章正文内容,下面案例可供参考

一、Ajax是什么?

Ajax(Asynchronous JavaScript and XML)是一种用于在不重新加载整个网页的情况下向服务器发送请求并接收响应的技术。它通过 JavaScript 来实现异步通信,允许你在网页上动态地加载数据、更新内容和与服务器交互,从而提升用户体验。

二、使用步骤

功能介绍
GET\POST以URL和表单的形式向浏览器发送请求并提交(页面会刷新)。
除此之外,也可以基于Ajax向后台发送请求(偷偷的发送请求)。

  • 依赖jQuery
  • 编写ajax代码
import json
from django.shortcuts import render
from django.http import HttpResponse

from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import TaskModelForm
from django.views.decorators.csrf import csrf_exempt
from app01.utils.bootstrap import BootstrapModelForm


class TaskModelForm(BootstrapModelForm):
    class Meta:
        model = models.Task
        fields = "__all__"
        widgets = {
            "detail": forms.TextInput
        }

def task_list(request):
    """任务列表"""
    # 去数据库获取数据
    queryset = models.Task.objects.all()
    page_object = Pagination(request, queryset, page_size=2)

    form = TaskModelForm()
    context = {
        "form": form,
        "page_string": page_object.html(),  # 生成页码
        "queryset": page_object.page_queryset,
    }
    return render(request, "task_list.html", context)

@csrf_exempt
def task_ajax(request):
    print(request.GET)
    print(request.POST)

    data_dict = {"status": True, 'data': [11, 22, 33, 44]}
    return HttpResponse(json.dumps(data_dict))

@csrf_exempt
def task_add(request):
    print(request.POST)
    # 1.用户输入数据进行校验(modelForm校验)
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {"status": True}
        return HttpResponse(json.dumps(data_dict))

    data_dict = {"status": False, 'error': form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))

{% 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,col-ms-2" style="margin-bottom: 20px ;position:relative;">
                                    {#                            <div class="form-control">#}
                                    <label>{{ field.label }}label>
                                    {{ field }}
                                    <span class="error-msg" style="color: red;position: absolute">span>
                                div>
                            div>
                        {% endfor %}
                        <div class="col-xs-12">
                            <button id="btnAdd1" type="button" class="btn btn-primary  ">提 交button>
                        div>
                    div>
                form>

            div>
        div>
        <div class="panel panel-default" style="margin-top: 20px;">
            
            <div class="panel-heading">
                <div>
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"> 任务列表 span>
                div>
            div>

            
            <table class="table">
                <thead>
                <tr>
                    <th>idth>
                    <th>标题th>
                    <th>级别th>
                    <th>负责人th>
                    <th>操作th>
                tr>
                thead>
                <tbody>
                {% for obj in queryset %}
                    <tr>
                        <th>{{ obj.id }}th>
                        <td>{{ obj.title }}td>
                        <td>{{ obj.get_level_display }}td>
                        <td>{{ obj.user_id }}td>
                        <td>
                            <a href="#" class="btn btn-primary btn-xs ">编辑a>
                            <a href="#" class="btn btn-danger btn-xs ">删除a>
                        td>
                    tr>
                {% endfor %}
                tbody>
            table>
        div>
        <ul class="pagination">
            {{ page_string }}
        ul>

        <div style="height: 1000px">div>
        <hr/>
        <h2>实例1h2>
        <input type="text" id="txtUser" placeholder="姓名">
        <input type="text" id="txtAge" placeholder="年龄">
        <input type="button" id="btn1" value="提交">

    div>



{% endblock %}

{% block js %}
    <script type="text/javascript">
        $(function () {
            {#            页面加载完就自动执行#}
            bindBtnAdd1Event();

            bindBtn1Event();
        })

        function bindBtnAdd1Event() {
            $("#btnAdd1").click(function () {
                $(".error-msg").empty();
                $.ajax({
                    url: '/task/add/',
                    type: "post",
                    data: $("#formAdd").serialize(),
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            alert("添加成功");
                            {#添加自动刷新#}
                            location.reload();
                        } else {
                            $.each(res.error, function (name, data) {
                                console.log(name, data)
                                $("#id_" + name).next().text(data[0]);
                            })
                        }
                    }
                })
            })
        }

        function bindBtn1Event() {
            $("#btn1").click(function () {
                $.ajax({
                    url: '/task/add/',
                    type: "post",
                    data: {
                        user: $("#txtUser").val(),
                        age: $("#txtAge").val()
                    },
                    dataType: "JSON",
                    success: function (res) {
                        console.log(res);
                        console.log(res.status);
                        console.log(res.data);
                    }
                })
            })
        }


    script>
{% endblock %}

二、订单管理

注意:
< input id=“btnAdd” type=“button” value=“新建订单2” class=“btn btn-success”>
< div class=“clearfix”>:清除浮动
< button id=“btnSave” type=“button” class=“btn btn-primary”>保 存

#order_list.html
{% extends 'layout.html' %}

{% block content %}
    <div class="container">
        <div>
{#          <input type="button" value="新建订单1" class="btn btn-primary" data-toggle="modal" data-target="#myModal">#}
            <input id="btnAdd" type="button" value="新建订单2" class="btn btn-success">
        div>
        <div class="panel panel-default" style="margin-top: 20px;">
            
            <div class="panel-heading">
                <div>
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"> 订单列表 span>
                div>
            div>

            
            <table class="table">
                <thead>
                <tr>
                    <th>idth>
                    <th>订单号th>
                    <th>名称th>
                    <th>价格th>
                    <th>状态th>
                    <th>负责人th>
                    <th>操作th>
                tr>
                thead>
                <tbody>
                {% for obj in queryset %}
                    <tr>
                        <th>{{ obj.id }}th>
                        <td>{{ obj.oid }}td>
                        <td>{{ obj.title }}td>
                        <td>{{ obj.price }}td>
                        <td>{{ obj.get_status_display }}td>
                        <td>{{ obj.admin.username }}td>
                        <td>
                            <input uid="{{ obj.id }}" type="button" class="btn btn-primary btn-xs btn-edit" value="编 辑">
                            <input uid="{{ obj.id }}" class="btn btn-danger btn-xs btn-delete" type="button"
                                   value="删 除">
                        td>

                    tr>
                {% endfor %}
                tbody>
            table>
        div>
        <ul class="pagination">
            {{ page_string }}
        ul>
    div>
    {#新建/编辑对话框#}
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×span>button>
                    <h4 class="modal-title" id="myModalLabel">新建h4>
                div>
                <div class="modal-body">
                    <form id="formSave">
                        <div class="clearfix">
                            {% for field in form %}
                                <div class="col-xs-6">
                                    <div class="form-group,col-ms-2"
                                         style="margin-bottom: 20px ;position:relative;">
                                        {#                            <div class="form-control">#}
                                        <label>{{ field.label }}label>
                                        {{ field }}
                                        <span class="error-msg" style="color: red;position: absolute">span>
                                    div>
                                div>
                            {% endfor %}

                        div>
                    form>
                div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取 消button>
                    <button id="btnSave" type="button" class="btn btn-primary">保 存button>
                div>
            div>
        div>
    div>

    {#删除对话框#}
    <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                        aria-hidden="true">×span>button>
                <h4>是否删除?h4>
                <p style="margin:10px 0px;">确定删除后,选取数据所有相关的数据都会被删除p>
                <p style="text-align: right ;">
                    <button id="btnConfirmDelete" type="button" class="btn btn-danger">确 定button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取 消button>
                p>
            div>
        div>
    div>

    {#删除对话框#}


{% endblock %}

{% block js %}
    <script type="text/javascript">
        var DELETE_ID
        var EDIT_ID
        $(function () {
            bindBtnAddEvent();

            bindBtnSaveEvent();

            bindBtnDeleteEvent();

            bindBtnConfirmDeleteEvent();

            bindBtnEditEvent();


        })

        function bindBtnAddEvent() {
            $('#btnAdd').click(function () {
                {#将正在编辑的ID设置为空#}
                EDIT_ID = undefined;

                {#清空对话框中的数据#}
                $("#formSave")[0].reset();

                $("#myModalLabel").text("新建")

                $('#myModal').modal('show')
            });
        }

        function bindBtnSaveEvent() {
            $("#btnSave").click(function () {
                {#清除错误信息#}
                $(".error-msg").empty();

                if (EDIT_ID) {
                    //编辑
                    doEdit();
                } else {
                    //添加
                    doAdd();
                }

                function doEdit() {
                    $.ajax({
                        url: '/order/edit/' + "?uid=" + EDIT_ID,
                        type: "post",
                        data: $("#formSave").serialize(),
                        dataType: "JSON",
                        success: function (res) {
                            if (res.status) {
                                alert("添加成功");
                                {##清空表单#}
                                $("#formSave")[0].reset();
                                {#关闭对话框#}
                                $('#myModal').modal('hide')
                                {#添加自动刷新#}
                                location.reload();
                            } else {
                                if (res.tips) {
                                    alert(res.tips);
                                } else {
                                    $.each(res.error, function (name, errorlist) {
                                        {#console.log(name, errorlist)#}
                                        $("#id_" + name).next().text(errorlist[0]);
                                    })
                                }

                            }

                        }
                    })
                }

                function doAdd() {
                    $.ajax({
                        url: '/order/add/',
                        type: "post",
                        data: $("#formSave").serialize(),
                        dataType: "JSON",
                        success: function (res) {
                            if (res.status) {
                                alert("添加成功");
                                {##清空表单#}
                                $("#formSave")[0].reset();
                                {#关闭对话框#}
                                $('#myModal').modal('hide')
                                {#添加自动刷新#}
                                location.reload();
                            } else {
                                {#console.log(res.error);#}
                                $.each(res.error, function (name, errorlist) {
                                    {#console.log(name, errorlist)#}
                                    $("#id_" + name).next().text(errorlist[0]);
                                })
                            }

                        }
                    })
                }

                {#向后台发送请求(添加ajax请求#}
            })
        }

        function bindBtnDeleteEvent() {
            $(".btn-delete").click(function () {
                {#alert("点击了删除");#}
                $("#deleteModal").modal('show');
                {#  获取当前行的ID并赋值给全局变量  #}
                DELETE_ID = $(this).attr("uid");

            })
        }

        function bindBtnConfirmDeleteEvent() {
            $("#btnConfirmDelete").click(function () {
                {#    确认删除按钮,将确定删除的id发送给后台#}
                $.ajax({
                    url: "/order/delete/",
                    type: "GET",
                    data: {
                        uid: DELETE_ID
                    },
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            {#alert("删除成功");#}
                            {#$('#deleteModal').modal('hide');#}
                            {#location.reload();#}
                            {#    在页面上将当前一行数据删除#}
                            {#$("tr[uid='"+DELETE_ID +"']").remove();#}
                            {#    要删除的id置为空#}
                            {#DELETE_ID = 0;#}
                            location.reload();


                        } else {
                            alert(res.error);
                        }
                    }
                })
            })
        }

        function bindBtnEditEvent() {
            $(".btn-edit").click(function () {
                var uid = $(this).attr("uid");
                EDIT_ID = uid

                {#设置对话框标题#}
                $("#myModalLabel").text("编辑")

                {#alert("点击了编辑");#}

                {#  发送ajax去后端获取当前行的相关数据#}
                $.ajax({
                    url: "/order/detail/",
                    type: "get",
                    data: {
                        uid: uid
                    },
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            $.each(res.data, function (name, value) {
                                $("#id_" + name).val(value);
                            })
                            $("#myModal").modal('show');
                        } else {
                            alert(res.error)
                        }
                    }
                })
                {#  在对话框中默认看到#}
            })
        }


    script>
{% endblock %}

注意:
订单号:form.instance.oid = datetime.now().strftime(“%Y%m%d%H%M%S”) + str(random.randint(1000, 9999))
当前管理员:form.instance.admin_id = request.session[“info”][“id”]

{% extends 'layout.html' %}

{% block content %}
    <div class="container">
        <div>
            {#            <input type="button" value="新建订单1" class="btn btn-primary" data-toggle="modal" data-target="#myModal">#}
            <input id="btnAdd" type="button" value="新建订单2" class="btn btn-success">
        div>
        <div class="panel panel-default" style="margin-top: 20px;">
            
            <div class="panel-heading">
                <div>
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"> 订单列表 span>
                div>
            div>

            
            <table class="table">
                <thead>
                <tr>
                    <th>idth>
                    <th>订单号th>
                    <th>名称th>
                    <th>价格th>
                    <th>状态th>
                    <th>负责人th>
                    <th>操作th>
                tr>
                thead>
                <tbody>
                {% for obj in queryset %}
                    <tr>
                        <th>{{ obj.id }}th>
                        <td>{{ obj.oid }}td>
                        <td>{{ obj.title }}td>
                        <td>{{ obj.price }}td>
                        <td>{{ obj.get_status_display }}td>
                        <td>{{ obj.admin.username }}td>
                        <td>
                            <input uid="{{ obj.id }}" type="button" class="btn btn-primary btn-xs btn-edit" value="编 辑">
                            <input uid="{{ obj.id }}" class="btn btn-danger btn-xs btn-delete" type="button"
                                   value="删 除">
                        td>

                    tr>
                {% endfor %}
                tbody>
            table>
        div>
        <ul class="pagination">
            {{ page_string }}
        ul>
    div>
    {#新建/编辑对话框#}
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×span>button>
                    <h4 class="modal-title" id="myModalLabel">新建h4>
                div>
                <div class="modal-body">
                    <form id="formSave">
                        <div class="clearfix">
                            {% for field in form %}
                                <div class="col-xs-6">
                                    <div class="form-group,col-ms-2"
                                         style="margin-bottom: 20px ;position:relative;">
                                        {#                            <div class="form-control">#}
                                        <label>{{ field.label }}label>
                                        {{ field }}
                                        <span class="error-msg" style="color: red;position: absolute">span>
                                    div>
                                div>
                            {% endfor %}

                        div>
                    form>
                div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取 消button>
                    <button id="btnSave" type="button" class="btn btn-primary">保 存button>
                div>
            div>
        div>
    div>

    {#删除对话框#}
    <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger alert-dismissible fade in" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                        aria-hidden="true">×span>button>
                <h4>是否删除?h4>
                <p style="margin:10px 0px;">确定删除后,选取数据所有相关的数据都会被删除p>
                <p style="text-align: right ;">
                    <button id="btnConfirmDelete" type="button" class="btn btn-danger">确 定button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取 消button>
                p>
            div>
        div>
    div>

    {#删除对话框#}


{% endblock %}

{% block js %}
    <script type="text/javascript">
        var DELETE_ID
        var EDIT_ID
        $(function () {
            bindBtnAddEvent();

            bindBtnSaveEvent();

            bindBtnDeleteEvent();

            bindBtnConfirmDeleteEvent();

            bindBtnEditEvent();


        })

        function bindBtnAddEvent() {
            $('#btnAdd').click(function () {
                {#将正在编辑的ID设置为空#}
                EDIT_ID = undefined;

                {#清空对话框中的数据#}
                $("#formSave")[0].reset();

                $("#myModalLabel").text("新建")

                $('#myModal').modal('show')
            });
        }

        function bindBtnSaveEvent() {
            $("#btnSave").click(function () {
                {#清除错误信息#}
                $(".error-msg").empty();

                if (EDIT_ID) {
                    //编辑
                    doEdit();
                } else {
                    //添加
                    doAdd();
                }

                function doEdit() {
                    $.ajax({
                        url: '/order/edit/' + "?uid=" + EDIT_ID,
                        type: "post",
                        data: $("#formSave").serialize(),
                        dataType: "JSON",
                        success: function (res) {
                            if (res.status) {
                                alert("添加成功");
                                {##清空表单#}
                                $("#formSave")[0].reset();
                                {#关闭对话框#}
                                $('#myModal').modal('hide')
                                {#添加自动刷新#}
                                location.reload();
                            } else {
                                if (res.tips) {
                                    alert(res.tips);
                                } else {
                                    $.each(res.error, function (name, errorlist) {
                                        {#console.log(name, errorlist)#}
                                        $("#id_" + name).next().text(errorlist[0]);
                                    })
                                }

                            }

                        }
                    })
                }

                function doAdd() {
                    $.ajax({
                        url: '/order/add/',
                        type: "post",
                        data: $("#formSave").serialize(),
                        dataType: "JSON",
                        success: function (res) {
                            if (res.status) {
                                alert("添加成功");
                                {##清空表单#}
                                $("#formSave")[0].reset();
                                {#关闭对话框#}
                                $('#myModal').modal('hide')
                                {#添加自动刷新#}
                                location.reload();
                            } else {
                                {#console.log(res.error);#}
                                $.each(res.error, function (name, errorlist) {
                                    {#console.log(name, errorlist)#}
                                    $("#id_" + name).next().text(errorlist[0]);
                                })
                            }

                        }
                    })
                }

                {#向后台发送请求(添加ajax请求#}
            })
        }

        function bindBtnDeleteEvent() {
            $(".btn-delete").click(function () {
                {#alert("点击了删除");#}
                $("#deleteModal").modal('show');
                {#  获取当前行的ID并赋值给全局变量  #}
                DELETE_ID = $(this).attr("uid");

            })
        }

        function bindBtnConfirmDeleteEvent() {
            $("#btnConfirmDelete").click(function () {
                {#    确认删除按钮,将确定删除的id发送给后台#}
                $.ajax({
                    url: "/order/delete/",
                    type: "GET",
                    data: {
                        uid: DELETE_ID
                    },
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            {#alert("删除成功");#}
                            {#$('#deleteModal').modal('hide');#}
                            {#location.reload();#}
                            {#    在页面上将当前一行数据删除#}
                            {#$("tr[uid='"+DELETE_ID +"']").remove();#}
                            {#    要删除的id置为空#}
                            {#DELETE_ID = 0;#}
                            location.reload();


                        } else {
                            alert(res.error);
                        }
                    }
                })
            })
        }

        function bindBtnEditEvent() {
            $(".btn-edit").click(function () {
                var uid = $(this).attr("uid");
                EDIT_ID = uid

                {#设置对话框标题#}
                $("#myModalLabel").text("编辑")

                {#alert("点击了编辑");#}

                {#  发送ajax去后端获取当前行的相关数据#}
                $.ajax({
                    url: "/order/detail/",
                    type: "get",
                    data: {
                        uid: uid
                    },
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            $.each(res.data, function (name, value) {
                                $("#id_" + name).val(value);
                            })
                            $("#myModal").modal('show');
                        } else {
                            alert(res.error)
                        }
                    }
                })
                {#  在对话框中默认看到#}
            })
        }


    script>
{% endblock %}


你可能感兴趣的:(前端,django,ajax)