如何将视图中的数组传递给 ajax 并在 Laravel 5 的控制器中访问?

Posted

技术标签:

【中文标题】如何将视图中的数组传递给 ajax 并在 Laravel 5 的控制器中访问?【英文标题】:How to pass an array in view to ajax and accessible in controller for Laravel 5? 【发布时间】:2020-01-16 21:08:08 【问题描述】:

我正在尝试使用 AJAX 将刀片视图中表格中的一组数据传递给我的控制器。当我单击保存按钮时,我能够返回响应,但数组数据集被忽略。估计数组数据没有传成功,因为我不知道正确的做法。

我尝试声明一个数组变量并存储数组数据集,但仍然没有任何反应。

刀片

@foreach ($qprbar1_hep1 as $d)
  @if ($d->particular <> 'Outcome Indicators' && $d->particular <> 'Output Indicators')
        <tr id="headerhep1 $d->id ">
        <td rowspan="1" class="item_part text-blue"> $d->particular  <input type="text" name="hep1part[]" id="hep1part[]" value=" $d->id " hidden></td>
        <td class="item_uacs text-teal"></td>
        <td contenteditable="false" class="item_ptq1 $d->id  text-red"><textarea name="hep1pt1[]" id="hep1pt1[]" cols="4" rows="2" maxlenght="20" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->PT1 </textarea></td>
        <td class="item_ptq2 $d->id  text-red"><textarea name="hep1pt2[]" id="hep1pt2[]" cols="4" rows="2" maxlenght="20" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->PT2 </textarea></td>
        <td class="item_ptq3 $d->id  text-red"><textarea name="hep1pt3[]" id="hep1pt3[]" cols="4" rows="2" maxlenght="20" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->PT3 </textarea></td>
        <td class="item_ptq4 $d->id  text-red"><textarea name="hep1pt4[]" id="hep1pt4[]" cols="4" rows="2" maxlenght="20" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->PT4 </textarea></td>
        <td class="item_pttot $d->id  text-green"><textarea name="hep1pt5[]" id="hep1pt5[]" cols="4" rows="2" maxlenght="20" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->PT5 </textarea></td>
        <td class="item_paq1 $d->id  text-red"><textarea name="hep1pa1[]" id="hep1pa1[]" cols="4" rows="2" maxlenght="20" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->PA1 </textarea></td>
        <td class="item_paq2 $d->id  text-red"><textarea name="hep1pa2[]" id="hep1pa2[]" cols="4" rows="2" maxlenght="20" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->PA2 </textarea></td>
        <td class="item_paq3 $d->id  text-red"><textarea name="hep1pa3[]" id="hep1pa3[]" cols="4" rows="2" maxlenght="20" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->PA3 </textarea></td>
        <td class="item_paq4 $d->id  text-red"><textarea name="hep1pa4[]" id="hep1pa4[]" cols="4" rows="2" maxlenght="20" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->PA4 </textarea></td>
        <td class="item_patot $d->id  text-green"><textarea name="hep1pa5[]" id="hep1pa5[]" cols="4" rows="2" maxlenght="20" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->PA5 </textarea></td>
        <td class="item_var $d->id  text-blue"><textarea name="hep1var[]" id="hep1var[]" cols="6" rows="2" maxlenght="20" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->variance </textarea></td>
        <td class="item_rem $d->id  text-orange"><textarea name="hep1rem[]" id="hep1rem[]" cols="27" rows="3" maxlenght="60" style="overflow:hidden;resize:none;text-align: center;border:0px;background-color: transparent;"> $d->remarks </textarea></td>
      </tr>
      @else
      <tr id="headerhep1 $d->id ">
        <td rowspan="1" class="item_part text-blue"> $d->particular </td>
        <td class="item_uacs text-teal"></td>
        <td class="item_ptq1 $d->id  text-red"></td>
        <td class="item_ptq2 $d->id  text-red"></td>
        <td class="item_ptq3 $d->id  text-red"></td>
        <td class="item_ptq4 $d->id  text-red"></td>
        <td class="item_pttot $d->id  text-green"></td>
        <td class="item_paq1 $d->id  text-red"></td>
        <td class="item_paq2 $d->id  text-red"></td>
        <td class="item_paq3 $d->id  text-red"></td>
        <td class="item_paq4 $d->id  text-red"></td>
        <td class="item_patot $d->id  text-green"></td>
        <td class="item_var $d->id  text-blue"></td>
        <td class="item_rem $d->id  text-orange"></td>
      </tr>
      @endif
@endforeach

脚本

<script>
  $('.save_hep1').on('click','.hep1_save', function()
      if ($('h4[name=ifsu_user_role]').text()  == 'Guest')
      
        alert('Guest users are not allowed to this function.');
        return false;
      
      else
    $("div#divLoading").addClass('show');
    var hep1part = [];
    var hep1pt1 = [];
    var hep1pt2 = [];
    var hep1pt3 = [];
    var hep1pt4 = [];
    var hep1pt5 = [];
    var hep1pa1 = [];
    var hep1pa2 = [];
    var hep1pa3 = [];
    var hep1pa4 = [];
    var hep1pa5 = [];
    var hep1var = [];
    var hep1rem = [];
        $.ajax(
          type: 'post',
          url: './editItem_hep1',
          data: 
              '_token': $('input[name=_token]').val(),
              'hep1part': [$("#hep1part").text()],
              'hep1pt1': [$("#hep1pt1").text()],
              'hep1pt2': [$("#hep1pt2").text()],
              'hep1pt3': [$("#hep1pt3").text()],
              'hep1pt4': [$("#hep1pt4").text()],
              'hep1pt5': [$("#hep1pt5").text()],
              'hep1pa1': [$("#hep1pa1").text()],
              'hep1pa2': [$("#hep1pa2").text()],
              'hep1pa3': [$("#hep1pa3").text()],
              'hep1pa4': [$("#hep1pa4").text()],
              'hep1pa5': [$("#hep1pa5").text()],
              'hep1var': [$("#hep1var").text()],
              'hep1rem': [$("#hep1rem").text()]
            ,
            success: function(data) 
                $('.errorTitle').addClass('hidden');
                $('.errorContent').addClass('hidden');
                if ((data.errors)) 
                    setTimeout(function () 
                        $('#editModalEnroll').modal('show');
                        toastr.error('Validation error!', 'Error Alert', timeOut: 3000);
                    , 500);
                    if (data.errors.title) 
                        $('.errorTitle').removeClass('hidden');
                        $('.errorTitle').text(data.errors.title);
                    
                    if (data.errors.content) 
                        $('.errorContent').removeClass('hidden');
                        $('.errorContent').text(data.errors.content);
                    
                
                else if ((data.msg)) 
                
                   $("div#divLoading").removeClass('show');
                  toastr.warning('Record not found! Record might has been deleted earlier or has been altered.', 'Oops Alert', timeOut: 5000);
                    $('.items' + id).remove();
                    $('.form-horizontal').show();
                
                else if (data.exmsg)
                  toastr.warning('Something went wrong.', 'Oops Alert', timeOut: 5000);
                  $("div#divLoading").removeClass('show');
                
                 else 
                    toastr.success('Successfully updated this record!', 'Success Alert', timeOut: 5000);

                    $("div#divLoading").removeClass('show');
                
            ,
            statusCode: 
            401: function()  
                window.location.href = 'login'; //or what ever is your login URI 
              
            
        );
      
    );
</script>

控制器

Public function editItem_hep1(Request $r)

    $barnumberedit = 12;

    try
    
    if ($qprbars = QprBarHEP1Value::where('qpr_bar_id','=',$barnumberedit)
        ->count() <= 0 or $qprbars = QprBarAEPValue::where('qpr_bar_id','=',$barnumberedit)
        ->count() <= 0)
    
        return response()->json(['danger' => true, 'created'=> true, 'msg' => 'Some program particulars are missing. Please generate before you can save changes. Update aborted.']);
    else
    
        foreach ($r->hep1part as $key => $v)
        
            $data = array(
              'qpr_bar_id'=>12,
              'PT1'=>$r->hep1pt1[$key],
              'PT2'=>$r->hep1pt2[$key],
              'PT3'=>$r->hep1pt3[$key],
              'PT4'=>$r->hep1pt4[$key],
              'PT5'=>$r->hep1pt5[$key],
              'PA1'=>$r->hep1pa1[$key],
              'PA2'=>$r->hep1pa2[$key],
              'PA3'=>$r->hep1pa3[$key],
              'PA4'=>$r->hep1pa4[$key],
              'PA5'=>$r->hep1pa5[$key],
              'variance'=>$r->hep1var[$key],
              'remarks'=>$r->hep1rem[$key],
              'updated_user_id'=>Auth::user()->id
            );
            QprBarHEP1Value::where('qpr_bar_id','=', $barnumberedit)->where('id','=',$v)->update($data);
            return response()->json($data);
        
        return back()->with('success','Program particulars updated successfully.');
    
     catch(\Exception $e)
        return response()->json(['success' => true, 'created'=> true, 'exmsg' => 'Sorry something went wrong.']);
     

【问题讨论】:

您正在寻找错误的 ID。 $("#hep1part").text() 应该是$("#hep1part[]").text(),这就是你的名字(没看剩下的代码)。 【参考方案1】:

我已经想通了。我不知道这种方法是否正确,但它确实有效。

@if (count($qprbar1_hep1))
    <script>
      //HEP
      $('.save_hep1').on('click','.hep1_save', function()
          if ($('h4[name=ifsu_user_role]').text()  == 'Guest')
          
            alert('Guest users are not allowed to this function.');
            return false;
          
          else
        $("div#divLoading").addClass('show');
            var hep1part = [
            @foreach ($qprbar1_hep1 as $d)
                " $d->id ", 
            @endforeach
            ];
            var hep1pt1 = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1pt1 $d->id ").val(), 
            @endforeach
            ];
            var hep1pt2 = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1pt2 $d->id ").val(), 
            @endforeach
            ];
            var hep1pt3 = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1pt3 $d->id ").val(), 
            @endforeach
            ];
            var hep1pt4 = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1pt4 $d->id ").val(), 
            @endforeach
            ];
            var hep1pt5 = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1pt5 $d->id ").val(), 
            @endforeach
            ];
            var hep1pa1 = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1pa1 $d->id ").val(), 
            @endforeach
            ];
            var hep1pa2 = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1pa2 $d->id ").val(), 
            @endforeach
            ];
            var hep1pa3 = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1pa3 $d->id ").val(), 
            @endforeach
            ];
            var hep1pa4 = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1pa4 $d->id ").val(), 
            @endforeach
            ];
            var hep1pa5 = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1pa5 $d->id ").val(), 
            @endforeach
            ];
            var hep1var = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1var $d->id ").val(), 
            @endforeach
            ];
            var hep1rem = [
            @foreach ($qprbar1_hep1 as $d)
                $("#hep1rem $d->id ").val(), 
            @endforeach
            ];
            $.ajax(
              type: 'post',
              url: './editItem_hep1',
              data: 
                  '_token': $('input[name=_token]').val(),
                  'bar_rec_id': $("#barnumberedit").val(),
                  'hep1part': hep1part,
                  'hep1pt1':  hep1pt1,
                  'hep1pt2': hep1pt2,
                  'hep1pt3': hep1pt3,
                  'hep1pt4': hep1pt4,
                  'hep1pt5': hep1pt5,
                  'hep1pa1': hep1pa1,
                  'hep1pa2': hep1pa2,
                  'hep1pa3': hep1pa3,
                  'hep1pa4': hep1pa4,
                  'hep1pa5': hep1pa5,
                  'hep1var': hep1var,
                  'hep1rem': hep1rem
                ,
                success: function(data) 
                    $('.errorTitle').addClass('hidden');
                    $('.errorContent').addClass('hidden');
                    if ((data.errors)) 
                        setTimeout(function () 
                            $('#editModalEnroll').modal('show');
                            toastr.error('Validation error!', 'Error Alert', timeOut: 3000);
                        , 500);
                        if (data.errors.title) 
                            $('.errorTitle').removeClass('hidden');
                            $('.errorTitle').text(data.errors.title);
                        
                        if (data.errors.content) 
                            $('.errorContent').removeClass('hidden');
                            $('.errorContent').text(data.errors.content);
                        
                    
                    else if ((data.msg)) 
                    
                       $("div#divLoading").removeClass('show');
                      toastr.warning('Record not found! Record might has been deleted earlier or has been altered.', '[HEP] Oops Alert', timeOut: 5000);
                        $('.items' + id).remove();
                        $('.form-horizontal').show();
                    
                    else if (data.exmsg)
                      toastr.warning('Something went wrong.', '[HEP] Oops Alert', timeOut: 5000);
                      $("div#divLoading").removeClass('show');
                    
                     else 
                        toastr.success('Successfully updated this record!', '[HEP] Success Alert', timeOut: 10000);
                        $("div#divLoading").removeClass('show');
                    
                ,
                statusCode: 
                401: function()  
                    window.location.href = 'login'; //or what ever is your login URI 
                  
                
            );
          
        );
    </script>
    @endif

【讨论】:

以上是关于如何将视图中的数组传递给 ajax 并在 Laravel 5 的控制器中访问?的主要内容,如果未能解决你的问题,请参考以下文章

如何从ajax将多个json数组传递给控制器​​?

如何将第二个viewcontroller文本字段值传递给第一个viewcontroller数组并在swift4中点击按钮时关闭

如何将 Struts 2 动作类中的 InputStream 值传递给 JSP 页面中的 Ajax 并将该值转换为 JSON 数组

如何在控制器中获取视图然后渲染数据并将其传递给 ajax

如何将复杂的键值参数表单视图传递给mvc中的控制器?

Django:如何通过 AJAX 将 PKID 列表传递给下一个视图,然后重定向