簡體   English   中英

Laravel使用Ajax更新數據庫

[英]Laravel Update Database with ajax

大家好,我正在使用laravel 5.7,並且嘗試發出ajax發布請求以更新數據庫。 Ajax將基於更改功能復選框發布。 例如,如果我關閉復選框,它將發送一個請求並將我的User表中的狀態更新為“不Inactive 嘗試后,我出現了405 (Method Not Allowed)錯誤405 (Method Not Allowed) 有人可以記錄我在做什么錯嗎? 很抱歉,如果我的代碼中有一些錯誤的代碼或語法,因為我是Ajax的新手。 任何幫助,將不勝感激。

阿賈克斯

$(document).ready(function(){
    $.ajax({
        type:'get',
        url:'{!!URL::to('findStatus')!!}',
        success:function(data){
            for(var i=0;i<data.length;i++){

                var checkBox = document.getElementById('switch-'+data[i].u_id);

                console.log(checkBox);

                if(data[i].status == "Active"){
                    $('#switch-'+data[i].u_id).prop('checked',true);
                }

                else if(data[i].status == "Inactive")
                {
                    $('#switch-'+data[i].u_id).prop('checked',false);
                } 


                $('#switch-'+data[i].u_id).change(function(){
                    $.ajax({
                        type: "POST",
                        url : '{!!URL::to('admin/{admin}')!!}',
                        success:function(data){
                            console.log(data);
                        }
                    });
                });
            }
        },
        error:function(data){
            console.log('ERROR');
        }
    });
});

路線

Route::resource('admin','AdminController');  << I'm using the update method from the resource controller

控制者

public function update(Request $request, $id)
{
    $user = User::find($id);
    if($user->status == "Active"){
        $user->status = "Inactive";
        $user->save();
    }else{
        $user->status = "Active";
        $user->save();
    }
    return response()->json($user);
}

形成

{!!Form::open(array('action'=>['AdminController@update',$item->u_id],'method'=>'POST','id'=>'update'))!!}
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="hidden" name="u_id" id="u_id" value="{{$item->u_id}}">
    <label class="custom-control custom-checkbox">
        <input type="checkbox" id="switch-{{$item->u_id}}" class="custom-control-input">
        <span class="custom-control-indicator"></span>
    </label>
    {{-- <button class="btn btn-primary">Update</button> --}}
{{Form::hidden('_method','PUT')}}
{!!Form::close()!!}

更新

我已經設法通過將u_id傳遞給我的發帖請求,方法是通過target.id獲取ID並將其與-分開。 這不是最優雅的方法,但它可以工作。 但是現在我收到一個錯誤

POST http://manageme.test/admin/%7B2%7D 500(內部服務器錯誤)

這是我在代碼中更新的內容。

$('#switch-'+data[i].u_id).change(function(e){

    console.log(e.target.id);

    var s = e.target.id;
    var split = s.split('-')[1];

    $.ajax({
        type: "POST",
        url: `{!!url('admin/')!!}/{${split}}`,
        data: { _token: "{{ csrf_token() }}", _method: "PUT" },
        success:function(data){
            console.log(data);
        }
    }); 
});

這些都在我的更新控制器中

public function update(Request $request, $id)
{
    $user = User::find($id);
    if($user->status == "Active"){
        $user->status = "Inactive";
        $user->save();
    }else{
        $user->status = "Active";
        $user->save();
    }
    return response()->json($user);
}

我還查看了開發工具的網絡選項卡中的錯誤,來自laravel的錯誤消息是message: "Trying to get property 'status' of non-object" 我認為在更新方法中找不到任何$user

而不是:“ {!! URL :: to('admin / {admin}')!!}}”寫:`{!! url('admin /')!!} / $ {data [i] .u_id} `並將_token和_method參數添加到您的ajax數據中,並編寫如下:

  $(document).ready(function () {
  $.ajax({
    type: 'get',
    url: '{!!url('findStatus')!!}',
    success: function (data) {
      data.forEach(d => {
        console.log(d);
        if (d.status == "Active") {
          $(`#switch-${d.u_id}`).prop('checked', true);
        }
        else if (d.status == "Inactive") {
          $(`#switch-${d.u_id}`).prop('checked', false);
        }
        $(`#switch-${d.u_id}`).change(function () {
          console.log(d);
          //changed###########
          $.ajax({
            type: 'POST',
            url: `{!!url('admin/')!!}/${d.u_id}`,
            data: { _token: "{{ csrf_token() }}", _method: "PUT" },
            success: function (data) {
              console.log(data);
            }
          });
          //###################
        });
      });
    },
    error: function (data) {
      console.log('ERROR');
    }
  });
});

我設法解決了問題,該問題來自試圖傳遞用戶的u_id並查找用戶數據的路由。 因此,我沒有在其中鍵入url,而是創建了一個變量以將路由和u_id一起傳遞。 這是代碼

阿賈克斯

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});


$.ajax({
    type:'get',
    url:'{!!url('findStatus')!!}',
    success:function(data){
        for(var i=0;i<data.length;i++){

            var checkBox = document.getElementById('switch-'+data[i].u_id);


            if(data[i].status == "Active"){
                $('#switch-'+data[i].u_id).prop('checked',true);
            }

            else if(data[i].status == "Inactive")
            {
                $('#switch-'+data[i].u_id).prop('checked',false);
            } 


            $('#switch-'+data[i].u_id).change(function(e){
                var s = e.target.id;
                var split = s.split('-')[1];
                var url = '{{route('admin.update','split')}}';

                $.ajax({
                    type: 'POST',
                    url: url,
                    data: { _token: "{{ csrf_token() }}", _method: "PUT" ,u_id: split},
                    success: function(data) {
                        console.log(data['message']);
                    }
                });
            });
        }
    },
    error:function(data){
        console.log('ERROR');
    }
});

更新方式

public function update(Request $request, $id)
{
    $user = User::find($request['u_id']);

    if($user->status == "Active")
    {
        $user->status = "Inactive";
        $user->save();
        return response()->json(['message' => 'Update to Inactive']);
    }else{
        $user->status = "Active";
        $user->save();
        return response()->json(['message' => 'Update to Active']);
    }       
}

不要忘記將meta標簽添加到csrf令牌的文檔標題中

 <meta name="csrf-token" content="{{ csrf_token() }}">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM