Laravel:Ajax更新到数据库

时间:2019-10-31 20:45:44

标签: ajax laravel

我只想通过ajax更新我的数据,但出现错误。 错误控制台:

  

POST http://abc.local/teachers/users/1 404(未找到)

这是我的控制器:

public function policyupdate(Request $request, $id)
              {

         $user = DB::table('users')->find($id);
        $user->update($request->all());
          return response()->json([
            'status' => 'success',
            'msg' => 'has been updated'
        ]);
         }

web.php:

Route::post('users/{user}','TeachersController@policyupdate') ;

js:

jQuery(document).ready(function(e)  {
  alert(1);
$('#update-policy').on('click', function(e) {
console.log('Update policy clicked!')
    e.preventDefault(e);

        $.ajax({
 type: "POST",
            url: "users/" + $('#update-policy').attr("value"),
        data:  $(this).serialize(),
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },

            success: function (data) {
          alert(updated);
              },

        });
    });
});

1 个答案:

答案 0 :(得分:2)

我只注意到了几个问题。

url: "users/" + $('#update-policy').attr("value"),

在ajax调用的URL中,您开头没有斜杠,因此该URL将相对于该函数所在页面的URL,而不是基本URL。要解决它,只需在开头添加斜杠

url: "/users/" + $('#update-policy').attr("value"),

另一个是您使用put方法输入了

<input type="hidden" name="_method" value="put" />

因此应放置Laravel路线(如果考虑到这是一条要更新的路线,这很有意义)

Route::put('users/{user}','TeachersController@policyupdate') ;

而且,正如您自己发现的那样,通过查询生成器,如果您使用update()而不是where()进行查询,则find()方法会起作用

$user = DB::table('users')->where('id', $id)->update( $request->all() );