删除Ajax记录的脚本无法正常工作



我有一个Ajax脚本,应该删除条目。它基本上可以工作,但当您单击删除按钮时,只有第一个会从所有记录的列表中删除。尽管如此,在重新加载页面后,消失的记录会出现,我想删除的记录也会被删除。如何解决这个问题?

<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#delete",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (){
$("#textpostdata").remove();
},
});
});
});

和html

<div id="textpost"> 
@foreach($post->comments as $com)
<div id="textpostdata" data-id="{{$com->comment_id}}">
<p><b>{{$com->author_name}}</b> · <i>{{$com->created_at->diffForHumans()}}</i></p>
<p>{{$com->comment}}</p>
@if(Auth::check())
@if(Auth::user()->id == $com->author_id)
<form action="{{route('delMusicComment', ['comment_id' => $com->comment_id])}}" method="post" id="formDelete">
@csrf @method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $com->comment_id }}">Удалить</button>
</form>
@endif
@endif
<hr>
</div>
@endforeach
</div>  

您对多个元素使用了相同的id
id应该是唯一的,如果您对其他元素使用相同的id,html只需将该id设置为第一个元素

您可以使用className而不是ID,如下所示:

HTML:

<button type="submit" class="btn btn-sm btn-outline-danger py-0 mt-4 delete" data-id="{{ $com->comment_id }}">Удалить</button>

jquery:

$("body").on("click",".delete",function(e){
//other lines of your jquery is ok, because you used $(this) in this line: var id = $(this).data('id');

Jquery-删除ajax后的条目:成功

var this_element = $(this); //get the active element, because you can not use $(this) in ajax:sucess!
$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (){
this_element.closest("div").remove(); //remove selected button's whole div!
},
});


注意:
当您使用className访问元素时,您可以使用$(this)
找到受事件影响的元素进行测试,使用此代码:console.log($(this));

你的html无效,因为如果有很多注释,你就有很多id为#textpostdata的div。你可以在它后面加上你的评论的id

<div id="textpost"> 
@foreach($post->comments as $com)
<div id="textpostdata-{{$com->comment_id}}" data-id="{{$com->comment_id}}">
<p><b>{{$com->author_name}}</b> · <i>{{$com->created_at->diffForHumans()}}</i></p>
<p>{{$com->comment}}</p>
@if(Auth::check())
@if(Auth::user()->id == $com->author_id)
<form action="{{route('delMusicComment', ['comment_id' => $com->comment_id])}}" method="post" id="formDelete">
@csrf @method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $com->comment_id }}">Удалить</button>
</form>
@endif
@endif
<hr>
</div>
@endforeach
</div> 

此外,您的查询选择器应该被修改,您的删除方法应该返回已删除的元素

$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (data){
$("#textpostdata" + data.comment_id).remove();
},
});

最新更新