首页 > 解决方案 > 如何在 laravel 8 中创建关系选择选项 ajax

问题描述

我尝试使用 ajax 在 laravel 8 中创建一个关系选择选项,但没有工作我在控制台中收到此错误:405 Method Not Allowed POST http://127.0.0.1:8000/decomptes/%7B%7B%20route( %20'getOperationsChantier'%20)%20%7D%7D 405(不允许的方法)

路线

Route::post('/getOperationsChantier', [DecompteController::class, 'getOperationsChantier'])->name('getOperationsChantier');

jQuery代码

$(document).ready(function(){

// When an option is changed, search the above for matching choices

    $('#chantiers').change(function(){
        $("#mySelect option").remove();
      //  $("#city option").remove();
        var id = $(this).val();
        $.ajax({
           url : "{{ route( 'getOperationsChantier' ) }}",
           data: {
             "_token": "{{ csrf_token() }}",
             "id": id
             },
           type: 'post',
           dataType: 'json',
           success: function( result )
           {
                $.each( result, function(k, v) {
                     $('#mySelect').append($('<option>', {value:k, text:v}));
                });
           },
           error: function()
          {
              //handle errors
              alert('error...');
          }
        });
}).change();

});

控制器中的功能:

function getOperationsChantier( Request $request )
    {
      $this->validate( $request, [ 'id' => 'required|exists:chantiers,id' ] );
      $chantierOperations = ChantierOperation::where('chantier_id', $request->get('id') )->get();
      $output = [];
      foreach( $chantierOperations as $chantierOperation )
      {
         $output[$chantierOperation->id] = $chantierOperation->operation_id;
      }
      return $output;
    }

有人可以帮我吗这是我第一次使用ajax

标签: ajaxlaravel

解决方案


推荐阅读