在 laravel 中使用 x-editable 更改动态状态

Change dynamic status with x-editable in laravel

我有 select 按钮,我可以在其中选择条目的状态。此状态来自 statuses table 并且它不是每个 table 中的一列(它是常规选项)。我想做的是在 x-editable 的帮助下更改 table 中的 status_id 列,但我不知道如何在 JavaScript 中获取动态数据。

这是我当前的表格,用于在我的评论的索引页面中显示状态,例如:

 <form action="{{route('updatebyajax', $rating->id)}}" method="post">
    {{csrf_field()}}
       <td class="text-center" style="width:100px;">
          <select class="form-control status" name="status_id">
            @foreach($statuses as $status)
              <option id="rating" class="rating" data-url="{{ route('updateratebyajax', $rating->id) }}" data-pk="{{ $rating->id }}" data-type="select" data-placement="right" data-title="Edit Rate" value="{{$status->id}}">{{$status->title}}</option>
           @endforeach
        </select>
    </td>
 </form>

所以我需要的基本上是从 statuses table 中获取信息并更改为 select。

更新

这里是我的 table 截图:

PS:这里是 select 按钮的默认示例: sample link

<a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a>
<script>
$(function(){
    $('#status').editable({
        value: 2,    
        source: [
              {value: 1, text: 'Active'},
              {value: 2, text: 'Blocked'},
              {value: 3, text: 'Deleted'}
           ]
    });
});
</script>

更新 2

审查数据库

状态Table

更新 3

我只是添加我的控制器方法和路由以防万一

控制器

public function updatebyajax(Request $request, $id)
  {
    return Rating::find($id)->update([
      'status_id' => $request->get('status_id'),
    ]);
  }

路线

Route::post('/updatebyajax/{id}', 'RatingController@updatebyajax')->name('updatebyajax');

更新 4

我在互联网上混合了几种解决方案,直到我最终在我的网络中得到 status 200 OK 但我的数据库仍然没有任何变化,这是我当前的代码:

controller

public function updatebyajax(Request $request, $id)
  {
    if (request()->ajax())
        {
            $ratings = DB::table('ratings')->select('status_id','id')->where('status_id', '=', $id)->get();
            return Response::json( $ratings );
        }
  }

AJAX

<script type="text/javascript">
$(".status").change(function() {
    $.ajax({
        type: "post", // for edit function in laravel
        url: "{{url('admin/updatebyajax')}}" + '/' + $(this).val(), // getting the id of the data
        data: {_token: "{{ csrf_token() }}",status: this.value }, //passing the value of the chosen status
        dataType: 'JSON',
        success: function (data) {
            console.log('success');
        },
        error: function (data) {
            console.log('error');
        }
    });
});
</script>

FORM

<form action="{{route('updatebyajax', $rating->id)}}" method="post">
                             {{csrf_field()}}
                              <td class="text-center" style="width:100px;">
                                <select id="{{ $rating->id }}" class="form-control status" name="status_id">
                                  @foreach($statuses as $status)
                                    <option value="{{$status->id}}">{{$status->title}}</option>
                                  @endforeach
                                </select>
                              </td>
                          </form>

更新 5

关于leih目前的答案我有这个:

Controller

public function updatebyajax(Request $request, $id)
  {
    // Note: should probably use a $request->has() wrapper to make sure everything present

    try {
        // you can also use the ID as a parameter, but always supplied by x-editable anyway
        $id = $request->input('pk');
        $field = $request->input('name');
        $value = $request->input('value');

        $rating = Rating::findOrFail($id);
        $rating->{$field} = $value;
        $rating->save();
    } catch (Exception $e) {
        return response($e->getMessage(), 400);
    }
  }

Route

Route::post('/updatebyajax', 'RatingController@updatebyajax')->name('updatebyajax');

Blade

//Select
<a
  href="#"
  class="status"
  data-type="select"
  data-pk="{{ $rating->id }}"
  data-value="{{ $rating->status_id }}"
  data-title="Select status"
  data-url="{{ route('updatebyajax') }}"
></a>

//JS

<script type="text/javascript">

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

$(function() {
    $('.status').editable({
      type:"select",
        source: [
            @foreach($statuses as $status)
                { value: {{ $status->id }}, text: {{ $status->title }} }
            @endforeach
        ],
    });
});
</script>

这是我得到的结果:

PS:如果我不使用 $.ajaxSetup({ headers: {.... 并在答案中使用 java 代码,我将收到此错误

Parse error: syntax error, unexpected ','

有什么想法吗??

我认为这对你有用。

  • 在select框的id中输入要更改的值的id
  • ajax jquery

    函数
    $(".status").change(function() {
        $.ajax({
            type: "PUT", // for edit function in laravel 
            url: "{{url('updatebyajax')}}" + '/' + this.id, // getting the id of the data 
            data: {_token: "{{ csrf_token() }}",status: this.value }, //passing the value of the chosen status
            dataType: 'JSON',
            success: function (data) {
                // some kind of alert or console.log to confirm change of status
            },
            error: function (data) {
                // error message
            }
        });
    });
    

希望对您有所帮助

使用带有 <select> 选项的 X-edtiable 时,最好查看 the documentation, but better to look at official examples and check the FAQ for what the back end needs。您不需要制作自己的表格或使用 X-editable 编写自己的 AJAX 请求(这就是重点)。根据您的要求,听起来代码应该类似于:

评级控制器

public function UpdateByAjax(Request $request)
{
    // Note: should probably use a $request->has() wrapper to make sure everything present

    try {
        // you can also use the ID as a parameter, but always supplied by x-editable anyway
        $id = $request->input('pk');
        $field = $request->input('name');
        $value = $request->input('value');

        $rating = Rating::findOrFail($id);
        $rating->{$field} = $value;
        $rating->save();
    } catch (Exception $e) {
        return response($e->getMessage(), 400);
    }

    return response('', 200);
}

路线

Route::post('/updatebyajax', 'RatingController@UpdateByAjax')->name('updatebyajax');

查看

注意:我没有在下面设置 CSRF 令牌,因为如果需要,它应该已经全局设置为 X 可编辑(例如,对于屏幕截图中的文本字段),或者通过其他一些机制设置。

<a
  href="#"
  class="status"
  data-type="select"
  data-pk="{{ $rating->id }}"
  data-name="status_id"
  data-value="{{ $rating->status_id }}"
  data-title="Select status"
  data-url="{{ route('updatebyajax') }}"
></a>
<script>
$(function() {
    // using class not id, since likely used with multiple records
    $('.status').editable({
        // Note: cleaner to format in the controller and render using the @json directive
        source: [
            @foreach($statuses as $status)
                { value: '{{ $status->id }}', text: '{{ $status->title }}' }
                @unless ($loop->last)
                    ,
                @endunless
            @endforeach
        ]
    });
});
</script>

附加参考:参见 Displaying Data blade documentation

中的 'Rendering JSON'