首页 > 解决方案 > 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>

如果有人可以帮我解决这个问题

标签: ajaxlaravel

解决方案


更好的做法是使用 methodroute()而不是url(). 你应该调用你的变量post。它是单一元素,但回到重点。你验证错了。在您的请求中,您没有变量:title并且bodyValidator 在更新数据之前返回错误。


推荐阅读