【发布时间】:2015-08-22 10:51:16
【问题描述】:
我想使用 ajax 删除记录。
查看
@foreach( $products as $product )
<tr>
<td>{{ $product->code }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->display }}</td>
<?php $time = date('d M, Y h:i:s A', strtotime($product->created_at)); ?>
<td>{{ $time }}</td>
<td>
<a href="{{ url('/admin/products/' . $product->id . '/edit') }}" class="links-dark edits pull-left">
<i class="fa fa-edit fa-lg"></i>
</a>
<div id="deleteTheProduct">
{!! Form::open(['method' => 'DELETE', 'id' => 'formDeleteProduct', 'action' => ['AdminProductsController@destroy', $product->id]]) !!}
{!! Form::button( '<i class="fa fa-trash fa-lg"></i>', ['type' => 'submit', 'class' => 'delete text-danger deleteProduct','id' => 'btnDeleteProduct', 'data-id' => $product->id ] ) !!}
{!! Form::close() !!}
</div>
</td>
</tr>
@endforeach
控制器
public function destroy( $id, Request $request ) {
$product = Product::findOrFail( $id );
if ( $request->ajax() ) {
$product->delete( $request->all() );
return response(['msg' => 'Product deleted', 'status' => 'success']);
}
return response(['msg' => 'Failed deleting the product', 'status' => 'failed']);
}
ajax 删除
$('.deleteProduct').on('click', function(e) {
var inputData = $('#formDeleteProduct').serialize();
var dataId = $('#btnDeleteProduct').attr('data-id');
$.ajax({
url: '{{ url('/admin/products') }}' + '/' + dataId,
type: 'POST',
data: inputData,
success: function( msg ) {
if ( msg.status === 'success' ) {
toastr.success( msg.msg );
setInterval(function() {
window.location.reload();
}, 5900);
}
},
error: function( data ) {
if ( data.status === 422 ) {
toastr.error('Cannot delete the category');
}
}
});
return false;
});
** 编辑 1 **:
如果我只返回 console.log(msg),这就是我得到的结果
Object {
id: "1",
code: "PROD-521420",
name: "Testing the product name",
category_id: "3",
short_description: "This is the short description"…
}
category_id: "3"
code: "PROD-521420"
created_at: "2015-06-07 23:00:31"
deleted_at: null
description: "This is the long description"
discount_price: "125.00"
display: "Enabled"
id: "1"
meta_description: "This is the meta description"
meta_keywords: "This is the meta keywords"
meta_title: "This is the meta title"
name: "Testing the product name"
price: "150.00"
short_description: "This is the short description"
updated_at: "2015-06-08 10:04:26"
问题是,这会删除产品,但只删除第一行而不是被点击的那一行。
我想删除被点击的产品。
谁能帮忙?
【问题讨论】:
-
delete调用不需要任何参数。只需执行$product->delete();。另外,使用DELETE作为ajax 方法,而不是POST。 -
@StuartWagner 我也试过了。问题是,它会删除表格的第一行,而与单击的行无关
-
如果您在控制器中的
delete()调用之前return $product;,并将console.log(msg);添加到您的ajax 调用中,您会得到什么? -
console.log(msg)没有显示任何内容。 -
您确定将 Ajax 请求发送到正确的路径吗?
标签: php ajax laravel laravel-5