財団のday08、sweetalertのAJAX組み合わせジャンゴ

models.py文件

from django.db import models

class User(models.Model):
    username=models.CharField(max_length=32)
    age=models.IntegerField()
    gender_choices=(
        (1,'male'),
        (2,'female'),
        (3,'other')
    )
    gender=models.IntegerField(choices=gender_choices)
    






urls.py文件

urlpatterns=[
    url(r'^admin/', admin.site.urls),
    #首页
    url(r'^$',views.home)
    
]







settings.py文件


STATICFILES_DIRS=[
    os.path.join(BASE_DIR,'static')
]

#另外注释csrf中间件








views.py文件

from django.shortcuts import render
from app01 import models
import time
from django.http import JsonResponse

'''
如果是ajax进行前后端交互,
通常后端会返回给ajax一个字典

'''
def home(request):
    '''
    思路整理:
        前提:
            查询出User表中全部数据
            locals()提交全部数据到home.html页面
    前端页面请求到后端以后:
    1.先判断是不是ajax请求
    2.是ajax请求的,返回字典:{'code':1000,'msg':''}
    3.获取删除数据对应的id值
    4.设置页面睡眠3秒钟
    5.执行删除
    6.然后给back_dic字典中的msg做赋值操作,数据已经删除
    7.通过Jsonresponse把back_dic 字典返回给前端页面
    
    '''
    #代码如下:
    if request.is_ajax():
        back_dic={'code':1000,'msg':''}
        delete_id=request.POST.get('delete_id')
        time.sleep(3)
        models.User.objects.filter(pk=delete_id).delete()
        back_dic['msg']='数据已经被我删除掉了'
        return JsonResponse(back_dic)
    
    user_queryset=models.User.objects.all()
    查询出User表中的全部数据
    return render(request,'home.html',locals())
    返回所有数据到home.html页面上
    
    
















homt.html文件

'''
首先动态配置静态文件
其次配置bootstrap文件和sweetalert文件的样式js和cs
'''
{% load static %}
<link rel='stylesheet' href='{% static 'boot3.7/css/boot.min.css' %}'>
<script src='{% static 'boot3.7/js/boot.min.js' %}'></script>

<link rel='stylesheet' href='{% static 'dist/sweetalert.css' %}'>
<script src='{% dist/sweetalert.min.js %}'></script>
<style>
    div.sweet-alert h2{
        padding:10px
    }
</style>

<div class='container-fluid'>
    <div class='row'>
        <div class='col-md-8 col-md-offset-2'>
            <h2>首先展示</h2>
            <br>
            <table class='table table-hover table-bordered table-striped'>
                <thead>
                <tr>
                    <th>序号</th>
                    <th>用户名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th class='text-center'>操作</th>         
                </tr>
                </thead>
                <tbody>
                {% for userobj in user_queryset %}
                    <tr>
                        <td>{{forloop.counter}}</td>    #计数
                        <td>{{userobj.username}}</td>
                        <td>{{userobj.age}}</td>
                        <td>{{userobj.get_gender_display}}</td>
                        固定用法获取gender,_display会自动加括号,所以此处display后面不能有括号
                        
                        <td class='text-center'>
                            <a href='#' class='btn btn-primary btn-sm'>编辑</a>
                            <a href='#' class='btn btn-danger btn-sm cancel userId={{userobj.pk}}'>删除</a>
                        </td>
                    </tr>
                
                {% endfor %}
                
                </tbody>
            </table>
        </div>  
    </div>
</div>

给删除绑定一个点击事件
<script>
    为删除添加一个绑定事件,利用cancel来指定删除事件
    $('.cancel').click(
        function(){
            朝后端发送ajax请求,如何拿到当前按钮所对应的数据的主键值id?
            先把$btn单独先存储起来,老师的思路是,添加自定义属性userId={{userobj.pk}}获取pk的值
            var $btn = $(this)
            swal({
                    title: "Are you sure?",
                    text: "You will not be able to recover this imaginary file!",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonClass: "btn-danger",
                    confirmButtonText: "Yes, delete it!",
                    cancelButtonText: "No, cancel plx!",
                    closeOnConfirm: false,
                    closeOnCancel: false,
                    showLoaderOnConfirm: true
                },
                function (isConfirm) {
                    if (isConfirm) {
                        //朝后端发送ajax请求
                        $.ajax({
                            url:'',
                            type:'post',
                            data:{'delete_id':$btn.attr('userId')}
                            //$btn指代当前被点击删除的按钮,$btn.attr指代当前删除按钮对应的属性,删除数据所对应的pk值
                            success:function(data){
                                if (data.code==1000){
                                    swal('猪脑泡泡龙','删了','success')
                                    //通过DOM操作,来直接操作标签,删除对应的数据
                                    //当前标签点父级标签点父级标签点移除
                                    $btn.parent().parent().remove()                             
                                }else{
                                    swal('有bug','未知错误','warning')
                                }
                            }
                            
                            
                        })

                    } else {
                        swal("Cancelled", "Your imaginary file is safe :)", "error");
                    }
                });
            
            
        }
    
    )


</script>














おすすめ

転載: www.cnblogs.com/ludundun/p/11972855.html