ajax - Laravel 在使用 ajax 时不更新值
问题描述
我正在尝试更新列的值,但它现在正在工作。我正在尝试更新页面上的视图,但它没有发生。没有错误仍然没有在数据库中更新。查看页面
<form style="" name="fbCommentCountform" id="fbCommentCountForm" action="{{ url('/posts/{$display_post->id}')}}" method="POST">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PUT">
<input type="text" name="commentCount" id="fbFormCommentCount">
<input type="text" name="visitCount" id="hiddenFormPostVisitCounter" value="{{ $display_post->visit_count }}">
</form>
控制器
public function update(Request $request, $id)
{
$image = $request->file('featured_img');
$posts = Post::findOrFail($id);
if(!empty($image))
{
$name = str_slug($request->title).'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/public/images');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$posts->featured_img = $name;
}
$posts->title = $request->title;
$posts->body = $request->body;
$posts->slug = $request->slug;
$posts->categories_id = $request->category;
$posts->description = $request->description;
$posts->visit_count = $request->visitCount;
$this->validate($request,[
'title' => 'required|string|max:255',
'body' => 'required'
]);
$posts->update();
return redirect('posts');
现在这里是ajax代码
<script>
let fbCommentCount = document.getElementById('fbCommentCount').getElementsByClassName('fb_comments_count');
setTimeout(function() {
document.getElementById('fbFormCommentCount').value = fbCommentCount[0].innerHTML;
var $formVar = $('#fbCommentCountForm');
let visitCount = document.getElementById('hiddenFormPostVisitCounter').value;
let visitCountPlusOne = parseInt(visitCount) + 1;
document.getElementById('hiddenFormPostVisitCounter').value = visitCountPlusOne;
$.ajax({
url: $formVar.prop('{{ url('/posts/{$display_post->id}') }}'),
method: 'PUT',
data: $formVar.serialize(),
});
}, 1000);
</script>
如果有人可以帮我解决这个问题
解决方案
更好的做法是使用 methodroute()
而不是url()
. 你应该调用你的变量post
。它是单一元素,但回到重点。你验证错了。在您的请求中,您没有变量:title
并且body
Validator 在更新数据之前返回错误。
推荐阅读
- java - 读取 API 响应的通用代码
- python - 如何根据用户输入更改 api 调用目的地?(python)
- angular - 看不到 ngBootstrap 设计的进度条。- 角 4+
- python - Mask-RCNN 中创建的会话在哪里?
- android - 如果每个字段都有键值对,如何设置微调器选择
- javascript - 使用 Vue.JS/Vuex 在哪里存储加载/错误状态?
- python - IOError: [Errno 121] 远程 I/O 错误
- angular - 角度延迟加载问题
- java - 在自定义 Listview 适配器中使用多个视图
- ios - 如何在 swift 4 中过滤 2d 模型数组,