【问题标题】:How to call controller method with array如何使用数组调用控制器方法
【发布时间】:2021-05-09 10:03:28
【问题描述】:

控制器 import() 从 csv 文件导入数据并使用数据数组重定向

//import data from csv file
return redirect('school/student/import')->with('result', $result);

import.blade.php 这是一个模态表单,向用户显示导入的数据。

 @if(Session::has('result'))
 @php
    $result = Session::get('result');
 @endphp
    <table class="table table-hover">
       <thead>
           ...
            <tr>
                @foreach($result as $datarow)
                   <tr>
                        <td>{{$datarow['student_no']}}</th>
                        ....
                   </tr>
                @endforeach
           </tbody>
        </table>
@endif
<button type="submit" class="btn btn-primary">Save changes</button>

@section('js')
    <script>
        @if(Session::has('result'))
            //$result = IS IT POSSIBLE TO ACCESS $result;
            
            $('#exampleModalCenter').modal('show');

            $("form#myForm").submit(function(event) {
                event.preventDefault();
                $('#exampleModalCenter').modal('hide');
                $.ajax({
                    type: "POST",
                    url: "savedata",
                    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    data: **$result**,
                    success: function(data){
                        window.location = '{{ url("school/student") }}';
                    },
                });
            });
        @endif
    </script>
@stop

点击提交后,我想用$result 数据数组调用Controller savedata()。 我尝试使用表单提交和 ajax 发布,但问题是因为 $result 是一个数组,很难通过。也无法从 JavaScript 访问会话值。

【问题讨论】:

  • 那么表单提交后你会得到什么?
  • @AhmadKarimi 表单无法使用数组提交

标签: ajax laravel post laravel-blade laravel-controller


【解决方案1】:

需要提供route name

路由/web.php

Route::post('savedata', 'ExampleController@savedata')->name('example.savedata');

路由命名后,需要将路由名称提供给ajax的URL。

$("form#myForm").submit(function(event) {
    event.preventDefault();
    $('#exampleModalCenter').modal('hide');
    $.ajax({
        type: "POST",
        url: '{{route("example.savedata")}}',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: $result,
        success: function(data){
            window.location = '{{ url("school/student") }}';
        },
    });
});

【讨论】:

  • 问题是访问并将$result 值传递给控制器​​。
  • 您需要在 ajax 中将数组编码为 json 并将 json 解码为控制器中的数组。在 ajax 中:data: {{JSON.stringify($result)}}
猜你喜欢
  • 1970-01-01
  • 2013-11-06
  • 2011-02-04
  • 1970-01-01
  • 2019-06-06
  • 1970-01-01
  • 2017-02-10
  • 2011-06-22
  • 1970-01-01
相关资源
最近更新 更多