Laravel ajax传递数据审核状态

laravel 开发过程中需要改变文章的状态,用来审核文章。从而在前台是否显示。在实际开发中并不是将文章删除而是改变文章的状态进行软删除

HTML前台渲染源码与javascript逻辑

<meta name="csrf-token" content="{{ csrf_token() }}">
<div class="box-body">
  <table class="table table-bordered">
     <tbody>
        <tr>
        <th style="width: 10px">#</th>
        <th>文章标题</th>
        <th>操作</th>
       </tr>
       @foreach($posts as $post)
        <tr>
         <td>{{$post->id}}.</td>
         <td>{{$post->title}}</td>
         <td>
           <button type="button" class="btn btn-block btn-default post-audit" post-id="{{$post->id}}" post-action-status="1" >通过</button>
           <button type="button" class="btn btn-block btn-default post-audit" post-id="{{$post->id}}" post-action-status="-1" >拒绝</button>
         </td>
        </tr>
       @endforeach
      </tbody>
   </table>
  </div>
{{$posts->links()}}
<script>
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$(".post-audit").click(function (event) {
    target = $(event.target);
    var post_id = target.attr("post-id");
    var status = target.attr("post-action-status");
    $.ajax({
        url: "/admin/posts/" + post_id + "/status",
        method: "POST",
        data: { "status": status },
        dataType: "json",
        success: function success(data) {
            if (data.error != 0) {
                alert(data.msg);
                return;
            }
            target.parent().parent().remove();
        }
    });
});
</script>

控制器页面进行数据处理并返回修改状态

/*
 * 修改文章的状态
 */
public function status(\App\Post $post)
{
    $this->validate(request(), [
        "status" => 'required|in:-1,1',
    ]);
    $post->status = request('status');
    $post->save();
    return [
        'error' => 0,
        'msg' => ''
    ];
}

OK这样就完事了

阅读 72

Comments