【问题标题】:Laravel -, Can't update more than one record using Fetch ApiLaravel -,不能使用 Fetch Api 更新多个记录
【发布时间】:2018-08-12 12:03:38
【问题描述】:

我想更新我的多条记录。但是只有第一条记录在更新,其他的没有..

我正在使用 fetch api 进行 ajax 调用,但我认为问题不在这里,因为我能够发送数组数据,我可以在浏览器开发部分看到。 (我的意思是,我可以发送多个id数据,没关系)

然后我尝试将它们保存在 foreach 循环中,但只有第一条记录在此循环中更新。

在控制器中

 public function approveComment(Request $request)
    {
      if ($request->ajax()) {
          $ids = $request->json()->all();
            foreach ($ids as $id) {
                $comment = Comments::find($id);
                $comment->comment_status = 1;
                $comment->save();
            }
    return response()->json("successful");
      } else {
          $comment = Comments::find($request->input('comment_id'));
          $comment->comment_status = 1;
          $comment->save();
          return back();
      }
    }

ajax 调用;

ajax.put('comments/approve',token,ids)
      .then(data => data.json())
      .then(log => console.log(log))
      .catch(err => console.log(err))

将方法放入 ajax 类中

 async put(url, token, data) {

        const response = await fetch(url, {
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json",
                "X-Requested-With": "XMLHttpRequest",
                "X-CSRF-Token": token
            },
            method: "put",
            credentials: "same-origin",
            body: JSON.stringify(data)
        });
        return response;
    }

【问题讨论】:

  • $ids 是否包含预期值?
  • 我在开发控制台上检查了它。它的 cmets id 为 json

标签: javascript ajax laravel fetch


【解决方案1】:

我发现了问题;

 public function approveComment(Request $request)
    {
      if ($request->ajax()) {
          $ids = $request->json()->all();
            foreach ($ids as $id) {
                $comment = Comments::find($id);
                $comment->comment_status = 1;
                $comment->save();
   //  return response()->json("successful"); (it was here)
            }
    return response()->json("successful"); (it should be in here, not in loop)
      } else {
          $comment = Comments::find($request->input('comment_id'));
          $comment->comment_status = 1;
          $comment->save();
          return back();
      }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-02
    • 2022-01-23
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多