Laravel通过按下href提交删除表单

时间:2017-08-10 14:03:16

标签: javascript jquery forms laravel

我在Laravel 5.4中有一个表,它显示有删除选项的新闻。 代码如下: news.blade.php:

@foreach($news as $article)
   <tr class="text-center">
       <td>{{ $article->title }}</td>
       <td>{{ $article->created_at }}</td>
       <td>{{ $article->views }}</td>
       <td>
          <a class="btn btn-primary btn-flat" href="#">
             <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
          </a>
       </td>
       <td>
           <a class="btn btn-warning btn-flat" href="#" onclick="event.preventDefault(); document.getElementById('delete-form').submit();">
                 <i class="fa fa-lg fa-trash"></i>
           </a>

           <form action="{{ route('delete-article') }}" method="POST" id="delete-form" style="display: none;">
                {{csrf_field()}}
                <input type="hidden" value="{{ $article->id }}" name="id">
           </form>
        </td>
   </tr>
@endforeach

我的问题是我如何告诉javascript准确提交紧靠a href旁边的表单,因为现在它将提交第一个匹配id的表单,该表单并不总是与点击的td相同一个href

修改 我知道我可以尝试使用jquery访问单击的href的父级,然后访问它的子窗体或使用jquery的close函数,但我正在寻找更稳定的东西。

4 个答案:

答案 0 :(得分:4)

在做任何事情之前,你的路线应该是(如果它还没有完成):
Route::delete(...)->name('delete-article');

我认为你可以这样做:

   <a class="btn btn-warning btn-flat" href="#" onclick="event.preventDefault(); document.getElementById('delete-form-{{ $article->id }}').submit();">
         <i class="fa fa-lg fa-trash"></i>
   </a>

   <form action="{{ route('delete-article') }}" method="POST" id="delete-form-{{ $article->id }}" style="display: none;">
        {{csrf_field()}}
        {{ method_field('DELETE') }}
        <input type="hidden" value="{{ $article->id }}" name="id">
   </form>

或使用Ajax

@foreach($news as $article)
   <tr class="text-center">
       <td>{{ $article->title }}</td>
       <td>{{ $article->created_at }}</td>
       <td>{{ $article->views }}</td>
       <td>
          <a class="btn btn-primary btn-flat" href="#">
             <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
          </a>
       </td>
       <td>
           <a class="btn btn-warning btn-flat" href="#" onclick="callAjax({{ $article->id }})">
                 <i class="fa fa-lg fa-trash"></i>
           </a>
        </td>
   </tr>
@endforeach

<script>
function callAjax(articleId) {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    })

    $.ajax({
        type: 'POST',
        url: '{{ route('delete-article') }}',
        data: {_method: 'DELETE', id: articleId}
    })
    .done(function (data) {
        // DO SOMETHING OR NOT
     }).error(function (err) {
        // DO SOMETHING OR NOT
     });
}

</script>

您必须在文档头中指定<meta name="csrf-token" content="{{ csrf_token() }}">。 (https://laravel.com/docs/5.4/csrf#csrf-x-csrf-token

答案 1 :(得分:1)

Benjamin Brasseur为您提供了一种使用AJAX的方法。 (顺便说一下,我认为这并不“狡猾”)

但是,使用您当前的JavaScript,您似乎只是提交了一个隐藏的表单。你为什么不使用真实的表格?

<td>
    <form action="{{ route('delete-article') }}" method="POST">
        {{ csrf_field() }}

        <input type="hidden" value="{{ $article->id }}" name="id" />

        <button type="submit" class="btn btn-warning btn-flat">
             <i class="fa fa-lg fa-trash"></i>
        </button>
    </form>
</td>

如果视觉效果不同,请调整<form>(使其成为内联块或其他内容)和<button>的样式以匹配旧<a>

答案 2 :(得分:0)

HTML

<tr id="parent-{{ $article->id }}">
  <td>{{ $article->title }}</td>
  <td>{{ $article->created_at }}</td>
  <td>{{ $article->views }}</td>
  <td>
    <a href="{{ route('route', $article->id) }}" id="{{ $article->id }}" data-method="DELETE" class="delete-btn"><i class="fa fa-fw fa-remove"></i></a>
  </td>
</tr>

加入你的脑袋:

<meta name="csrf-token" content="{{ csrf_token() }}">

我的脚本与我的刀片tempate在同一个文件中 JS

<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $(document).on('click', '.delete-btn', function(e) {
        var $this = $(this),
            $id = $(this).attr('id');

        if (confirm('Are you sure you want to delete this post?')) {
            $.post({
                type: $this.data('method'),
                url: $this.attr('href')
            }).done(function (data) {
                $('#parent-' + $id).slideUp(300, function() {
                    $(this).remove();
                });
            }).fail(function (data) {
                console.log(data);  
            });
        }

        e.preventDefault();
    });
    </script>

在您的控制器中

public function destroy($id)
{
        Article::find($id)->delete();

        return response()->json(['success' => 'Article ID: ' . $id . ' has been deleted']);
}

您的路线:

Route::delete('/delete/{post}', 'Controller@destroy')->name('delete');

答案 3 :(得分:0)

HTML

<a href="#" onclick="deleteStudent()" class="nav-link">
    <span><i class="fa fa-fw fa-trash mr-1"></i> Delete Student</span>
</a>
<form id="deleteStudentForm" action="{{ route( 'students.destroy', $student->id ) }}" method="post">
    @csrf
    @method('DELETE')
</form>

JavaScript

@section('js_after')
    <script>
        function deleteStudent () {
            event.preventDefault();
            if ( confirm( "Do you really want to delete student '{{$student->stu_name}}' ?" ) ) {
                // get delete form
                var deleteForm = document.getElementById( 'deleteStudentForm' );
                // submit delete form
                deleteForm.submit();
            } else {
                return false;
            }
        }
    </script>
@endsection