Laravel:使用Ajax更新数据库。接下来我该怎么办?

时间:2019-07-23 19:07:37

标签: ajax database laravel

在使用AJAX时,我需要有人的指导来帮助我构建功能更新数据库。当我单击“接受”按钮时,Ajax请求将发送到服务器,并且服务器将执行字段 post_status 的UPDATE值。首先,字段 post_status 的值为“待处理”,在执行查询UPDATE之后,该值将更改为“已接受”。 接下来我该怎么办?请帮我。 非常感谢您的帮助。

  • “帖子”表的数据库:
C++
  • 视图:
struct
  • 代码Javascript:
post_id user_id    title       content      DateTime      post_status
1          1      Title 1     Content 1       Time         pending
2          2      Title 2     Content 2       Time         pending
3          3      Title 3     Content 3       Time         pending
4          4      Title 4     Content 4       Time         pending
5          5      Title 5     Content 5       Time         pending
  • Controller的功能list_post_ajax:
<table class="table table-bordered">
    <thead class="thead-inverse">
        <tr>
            <th>Post ID</th>
            <th>User ID</th>
            <th>Name User</th>
            <th>Title</th>
            <th>Content</th>
            <th>Datetime</th>
            <th>Status</th>
            <th>Accept</th>
        </tr>
        </thead>
        <tbody>
            @foreach ($posts as $row)
            <tr id="{{ $row->post_id }}"> 
                <td>{{$row->post_id}}</td>
                <td>{{$row->user_id}}</td>
                <th>{{$row->users->name}}</th>
                <td>{{$row->post_title}}</td>
                <td>{{$row->post_content}}</td>
                <td>{{$row->post_datetime}}</td>
                <td>{{$row->post_status}}</td>      {{-- The status of post that I wanna change the value to "accepted"  --}}
            <td>
                <button class="btn btn-success accept-btn" data-postID="{{$row->post_id}}">Accept</button>
            </td>
            </tr>
            @endforeach
        </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。这将遵循您的代码。使用$myObject->save();保存新记录或更新旧记录。

更改视图

<td id="td{{$row->post_id}}">{{$row->post_status}}</td>

在控制器上

$postId = $request->get('postId');

$post = App\Post::find($postId);

$post->post_status= 'accepted';

$post->save();

return response()->json(['success'=>$postId,'message'=>'accepted']);

在JS上

      $.ajax({
            type: "POST",
            url: "{{route('posts.list_post_ajax')}}",      
            data: { postId: postId },
            dataType: 'JSON',
            success :function(response) {
                console.log(response);
                 $('td'+postId).html(response.message);
            },
        });

编辑:我在Controller上更新了我的答案。您应该看看Eloquent文档

相关问题