我正在尝试使用 jquery ajax 从表中删除一行。经过几次尝试后,我无法弄清楚为什么我的代码(删除部分)不起作用,因为我是 ajax 和 javascript 的新手。从服务器使用 ajax 加载数据工作正常,脚本没有控制台错误。当我按下删除键时,我在网络选项卡上看不到任何内容。这是我的代码:
路由.php
Route::delete('users/{id}','AjaxController@destroy');
AjaxController.php
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
}
查看:
<table id="users" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody id="abc">
</tbody>
</table>
脚本:
$(document).ready(function(){
var $tbody = $('#abc');
// getting data from server
$.ajax({
type : 'GET',
url : 'api/users',
success: function(users) {
$.each(users, function(i, user){
$tbody.append('<tr id="user_' + user.id + '"><td>'+user.name+'</td><td>'+user.phone+'</td><td><button type="button" class="btn btn-xs btn-danger" id="delete" value="'+user.id+'" name="button">Delete</button></td></tr>');
});
},
error: function(){
alert('error loading data');
}
});
// deleting data
$('#delete').on('click', function(e){
var user_id = $(this).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
e.preventDefault();
var user = {
id : user_id
};
$.ajax({
type: 'DELETE',
url : '/user/'+user.id,
success : function(deleteUser)
{
$("#user_" + user_id).remove();
},
error : function()
{
alert('error deleting data');
}
});
}); // deleting block ends
});
});
最佳答案
这里的问题是您一遍又一遍地使用相同的 id
。然而,这个问题因您动态插入内容而变得更加复杂,但您的事件绑定(bind)仅观察页面加载时可用的元素。让我们解决所有这些问题。首先,我们需要取消 ID。
class="btn btn-xs btn-danger" id="delete" value="'+user.id+'"
需要改成
class="btn btn-xs btn-danger btn-delete" value="'+user.id+'"
太棒了。我们使用了 btn-delete
。这并非特定于此特定用户功能。按照 CRUD 的工作方式,您应该能够为通过 CRUD Controller 与之交互的每个模型重复使用此代码。
现在我们需要委托(delegate)我们的事件绑定(bind),我们还将使按钮更通用,如前一段所述。为了帖子的长度,我只会展示你应该如何设置你的 javascript。
$('table').on('click', '.btn-delete', function(e){
e.preventDefault();
var $btn = $(this),
$table = $btn.closest('table');
$.ajax({
url: $table.data('resource') . '/' . $btn.val(),
type: 'delete'
}).done(function(response){
console.log(response);
}).error(function(x,t,m){
console.warn(x,t,m);
});
});
token 可以移动到文件的顶部
,不需要嵌套:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
最后,我们需要将我们的 data-resource
属性附加到我们的表中:
<table ... data-resource="users"
现在您已经有了一个可重用的模型,只需要将 data-resource="model"
属性附加到您的表格,以及一个类为 btn-delete< 的按钮
具有实体的 id
的值。
关于javascript - Laravel 简单的 crud 与 jquery ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38910194/