我想使用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"
事实是,这会删除产品,但只会删除第一行,而不是单击的行。
我要删除单击的产品。
有人可以帮忙吗?
您的问题在这里:
var dataId = $('#btnDeleteProduct').attr('data-id');
您将只获得第一个,因为您在所有按钮上使用重复的ID。因此,一个ID嘶嘶声查询将使您获得第一个。
如果您在删除控制器中的dd($ id)您将看到此信息。它始终是第一个的ID。您可以通过相对于event.target进行查询来获取data-id属性。
您将要使用调试器。您的回叫内的语句对此进行了测试,但查询应类似于:
$(e.target).attr('data-id');
要么
$(this).attr('data-id');
事件目标应该是被单击的按钮,然后在该按钮上设置数据ID,因此您只需要通过事件对其进行查询。