Ajax 功能无法在不刷新页面的情况下正常删除

Posted

技术标签:

【中文标题】Ajax 功能无法在不刷新页面的情况下正常删除【英文标题】:Ajax function not working properly for deleting without refreshing page 【发布时间】:2019-11-16 00:00:35 【问题描述】:

我正在解决一个问题,我需要在不刷新列表页面的情况下删除数据库中的条目。但是,使用我创建的 ajax 函数和视图,数据被删除但成功函数未更改为 true。列表页面按原样显示,手动刷新已删除数据时不显示。另外,由于我是 ajax 新手,所以我不太了解在 ajax 中的数据字典中要删除什么内容。我在代码中做错了什么?请在不刷新页面的情况下帮助我这样做。(我需要留在中心列表页面上)。提前致谢。

<script>

$(document).on('click','#delete',function()
 var a ;
 a=confirm("Do you really want to delete the user?");
if(a==true)
 var url = "% url 'NewApp:centredelete' pk=1%"
 var id = $(this).attr('name')
 $.ajax(

    type:"GET",
    url: url.replace('1',id),
    data:
          delete:true
    ,
    success: function( data )
    
        if(data.success == true)
           $(id).remove();

         

     
     )
);
</script>

views.py

def CentreDeleteView(request, pk):
data = 'success': False
centre = Centre.objects.get(pk=pk)
print(centre)
if request.method == 'GET':
    try:
        if centre:
            centre.delete()
            data['success'] = True

        else:
            data['success'] = False
            data['error'] = "unsuccessful!"
    except Centre.DoesNotExist:
        return redirect('/NewApp/centrelist')
return JsonResponse(json.dumps(data))

【问题讨论】:

不相关,但如果您使用的是JsonResponse,那么您不必使用json.dumps 'var id = $(this).attr('name')' 返回什么?您是否尝试过使用 $(id).remove();有真实的身份证? name= modelname.id 在我的模板中。是的,id 有实际的 id。 【参考方案1】:

您没有阻止默认提交事件的发生。

$(document).on('click','#delete',function(event)
  event.preventDefault();
  ..
);

【讨论】:

这似乎没有任何作用。

以上是关于Ajax 功能无法在不刷新页面的情况下正常删除的主要内容,如果未能解决你的问题,请参考以下文章