Django与AJAX

AJAX

前两篇博客中已经介绍了ajax的基本情况,这篇博客就针对原理进行实验和测试。主要是ajax在文件上传中的作用以及与SweetAlert插件配合实现删除操作的二次确认,代码均挑选ajax最核心的逻辑部分,html的部分不作详细展示。

使用ajax上传文件

// 上传文件示例
$("#b3").click(function () {
  var formData = new FormData();   // 实例化一个FormData对象
  formData.append("csrfmiddlewaretoken", $("[name='csrfmiddlewaretoken']").val());
  formData.append("f1", $("#f1")[0].files[0]);
  $.ajax({
    url: "/upload/",
    type: "POST",
    processData: false,  // 告诉jQuery不要去处理发送的数据
    contentType: false,  // 告诉jQuery不要去设置Content-Type请求头
    data: form,
    success:function (data) {
      console.log(data)
    }
  })
})

SweetAlert插件

官网 这里不做教程,只是简单的介绍二次确认的用法

第一步:模板中引入sweetalert.min.js

第二步:jQuery找到相应的button按钮,添加事件,代码如下;

第三步:then之后的内容是主逻辑部分,前后端的数据交换使用的ajax

【注意】里边使用到了h5的箭头函数,他的一大特点就是this指向的外层

<script>
    $('#bt').click(function () {
         swal({
                title: "Are you sure?",
                text: "Once deleted, you will not be able to recover this imaginary file!",
                icon: "warning",
                buttons: true,
                dangerMode: true,
            })
                .then((willDelete) => { //h5里的箭头函数,你会改变this的指向
                    if (willDelete) {
                        $.ajax({
                            {#url: '/publisher_del/' + $(this).attr('del_id') + '/',#}
                            url: '/makesure/',
                            success: (res) => {  
                                // 后端删除成功后,在这里对前端进行数据删除任务
                                if (res.status) {
                                    swal("Poof! Your imaginary file has been deleted!", {
                                        icon: "success",
                                    });
                                }
                            }
                        })

                    } else {
                        swal("Your imaginary file is safe!");
                    }
                });
    })
</script>
原文地址:https://www.cnblogs.com/jjzz1234/p/11620021.html