首页 > 解决方案 > laravel ajax 意外结束 json 输入

问题描述

大家好,我很绝望,我没有完全理解 Ajax 的这种语法/概念。

我的页面上有 2 个表格。根据隐藏字段的值,我的控制器中的某个逻辑将被执行。其实很简单——我想。我试图将一个数组从我的 ajax 传递给我的控制器,然后将它传递回我的视图。我知道这没有多大意义。但我试图了解它是如何工作的。第一个逻辑被执行,但另一个让我收到这个错误:
jqXHR is : [object Object] textStatus is : parsererror errorThrown is : SyntaxError: Unexpected end of JSON input

这是为什么 ?各位大佬能不能给我个建议。

更新

我尽量不放整个代码,而只是将其简化为主要问题。但由于它引起了根本原因的混淆,我将展示可能相关部分的整个代码。我将问题编辑到下面。

 <center>
        <div class="col-md-12">
        <h3>xlsx, xls, ods, csv to Text</h3>
        <form id="xlsForm" enctype="multipart/form-data">
            @csrf
            <input type="file" name="excelfile" />
            <input name ="loadSubmit" id="loadSubmit" type="submit"/>
            <input type ="hidden" name="load" value="0">
        </form>
    </div>
    </center>

    <div class ="row">
        <div class ="col-md-3">
            <div class="container mt-5">
                <h2 id="words" class="mb-4">Skills found</h2>
            </div>
                <form id="xlsFormUpdate"  enctype="multipart/form-data">
                    <input type ="hidden" name="load" value="1">
                    <div id="inner">
                    </div>
          <input name ="updateSubmit" id="updateSubmit" type="submit"/>
                </form>

        </div>
    <div class ="col-md-9">
    @include('layouts.partials.datatable')
    </div>

    </div>

控制器:

  if ($request->input('load') == '0') {

         //some code -- this works fine 

return response()->json($data);  //This data can be send - no problem


     } elseif (($request->input('load') == '1')) {

      $data = $request->post('checkbox_array'); 
 
         return response->json($data); // i tried json_encode too .. not working.

     }

jQuery代码

  $(document).ready(function(){

    $('#xlsForm').submit(function uploadFile(event){
        event.preventDefault();

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url: "{{route('ExcelToArray')}}",
            method: 'POST',
            data: new FormData(this),
            dataType: 'JSON',
            contentType: false,
            cache: false,
            processData: false,
            success:function (response) {
               $("#inner").empty();
                $.each(response,function(index,value){
                    $("#inner").append
                    ('<div class="row">' +
                        '<div class="col-xs-2">'+
                        '<input type="checkbox" class="'+value+'" value="'+value+'" name="checkbox[]"  checked >  <label style="font-weight: bold" for="skillChoice_'+index+'">'+value+' </label>' +
                        '</div>'+
                        '<div class="col-xs-1">'+
                        '<input class="'+value+'" type="number" name="weight[]" min="1" max="3" value="1"> '+
                        '</div>'+
                    '</div>');
                });
            }
          
        });
    });


    $('#xlsFormUpdate').submit(function uploadFile(event) {
        event.preventDefault();
        var checkbox_array = [];

        $('input[type=checkbox]').each(function (index,value) {

            if (this.checked)
            {
                checkbox_array.push(1);
            }
            else {
                checkbox_array.push(0);
 
            }
        });
           
        let checkbox_s = JSON.stringify(checkbox_array)

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        
        $.ajax({
            url: "{{route('ExcelToArray')}}",
            method: "POST",
            data: {checkbox_array:checkbox_s},
            dataType: 'JSON',
            contentType: false,
            cache: false,
            processData: false,

            success: function (response) {
                alert('The Response is ' + response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('jqXHR is : ' + jqXHR
                    + 'textStatus is : ' + textStatus
                    + ' errorThrown is : ' + errorThrown);

            },
              

        })
    });          





    });

标签: javascriptphpjqueryajaxlaravel

解决方案


当使用ajax submit 事件向控制器发送数据时,字段中的数据data: {checkbox_array:checkbox_s},将被发送到控制器。由于load从未发送过输入字段,因此该elseif (($request->input('load') == '1'))子句永远不会为真,并且控制器永远不会进入该部分并且永远不会返回正确的响应。必须像这样更改数据 var my_datas JSON.stringify({mydata:checkbox_array, load: "1"});,然后在 ajax 中可以像这样发送数据data:my_datasload然后可以在控制器中处理该字段。


推荐阅读