2017-04-19 37 views
0

我正在动态填充表,当我尝试连接或插入值到从控制器获取的JSON时卡住了。我想插入这个值,因为我需要显示一个图像,所以我插入一个带有来自JSON的路由的HTML标记。这是我的代码。在AJAX响应中插入JSON值

控制器

public function consultaProd2(Request $request) 
{ 
    $almacenes = Almacen::orderBy('nombre')->lists('nombre', 'id'); 
    $fechas = explode(' ', $request['RangoFecha']); 
    $fechaInicial = $fechas[0].' 00:00:00'; 
    $fechaFinal = $fechas[2].' 23:59:59'; 

    $productos = Producto::whereBetween('created_at', [$fechaInicial, $fechaFinal]) 
        ->where('almacen_id', '=', $request['Almacen']) 
        ->get(); 
    return response()->json($productos); 
} 

脚本

<script type="text/javascript"> 
 
    function llenar(response, index, value) 
 
    { 
 
     $('#example1').DataTable({ 
 
      "destroy": true, 
 
      "data": response, 
 
      "scrollX": true, 
 
      "columns":[ 
 
       {"data":"img"}, 
 
       {"data":"id"}, 
 
      ] 
 

 
     }); 
 
    } 
 
</script> 
 

 
<script type="text/javascript"> 
 
    function consultaProducto(){ 
 
     var tablaDatos = $('#datos'); 
 
     var token = $("#token").val(); 
 
     var route = '<?= url('producto/consultaProducto') ?>' 
 
     var data = {}; 
 
     data.Almacen = $('select[name=Almacen]').val(); 
 
     data.RangoFecha = $('input[name=RangoFecha]').val(); 
 
       $.ajax({ 
 
        url: route, 
 
        headers: {'X-CSRF-TOKEN': token}, 
 
        data: data, 
 
        method: 'POST', 
 
        statusCode: { 
 
         400: function() { 
 
         } 
 
        } 
 
       }).done(function(response){ 
 
        $.each(response, function(index, value){ 
 
         if(response[index].pathImg == null) 
 
          var img = "/documento/valach/noimg.png"; 
 
         else 
 
          var img = response[index].pathImg; 
 
         var img = "/documento/valach/noimg.png"; 
 
         response[index].img = "<img src="+img+">"; 
 
         //console.log(response); 
 
         llenar(response, index, value); 
 
        }); 
 

 
       }).fail(function(response){ 
 
       }); 
 
      } 
 
     } 
 
     return false; 
 
    }

例如,如果查询得到3个阵列和我打印id它仅示出了信息机智没有任何错误,但是当我使用data:img这是我插入的值时,它会抛出以下错误,之后它会填充表并显示图像。

Error image here

和行随着信息到达,但如果我只得到查询1个阵列,它填补了表没有任何错误。希望你能帮助我,谢谢。

回答

0

您在回路内呼叫llenar(),即每次迭代一次。循环结束后应该调用它。你应该真的使用一些{ }来避免当你(或其他人)在3周内重新调查代码时出现混淆:)

$.each(response, function(index, value){ 
    var img; 
    if (response[index].pathImg == null) { 
    img = "/documento/valach/noimg.png"; 
    } else { 
    img = response[index].pathImg; 
    } 
    //var img = "/documento/valach/noimg.png"; ??? 
    response[index].img = "<img src="+img+">"; 
}); 
llenar(response, index, value);