【发布时间】:2019-12-01 21:17:29
【问题描述】:
在使用 AJAX 时,我需要有人指导帮助我构建功能更新数据库。当我单击接受按钮时,Ajax 请求将发送到服务器,服务器将执行字段 post_status 的 UPDATE 值。一开始,字段 post_status 的值为“pending”,执行查询 UPDATE 后,该值将变为“accepted”。 接下来我该怎么办?请帮我。 非常感谢您的帮助。
- Posts 表的数据库:
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
- 观点:
<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>
- 代码Javascript:
<script>
$(document).ready(function () {
$('.accept-btn').click(function(){
var postId = $(this).attr('data-postID');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "{{route('posts.list_post_ajax')}}",
data: { postId: postId },
dataType: 'JSON',
success :function(response) {
console.log(response);
},
});
})
});
</script>
- Controller的list_post_ajax函数:
public function list_post_ajax(Request $request)
{
if(request()->ajax()){
$postId = $request->get('postId');
return response()->json(['success'=>$postId]);
// What's I should do next?
// Pls help me.
}
}
【问题讨论】: