dongxian6715 2019-08-08 17:55
浏览 535

json_encode和JSON.parse错误:SyntaxError:JSON.parse:JSON数据第2行第43行的JSON数据之后的意外非空白字符

So, I've been trying to send an array from a php file to a script through JSON, using json_encode, but whatever I do, I keep getting the same error:

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 43 of the JSON data

Now, I've used jsonlint to validate the JSON received through json_encode, but it shows as not valid.

Here's my PHP code/query:


<?php

    require_once '../../DAO/model.php';

    $cd = $_POST['cd'];

    $query = "SELECT ID,name FROM user WHERE cost_center = '$cd' order by name";      
    $results = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($results)){        
        echo json_encode($row); 
    }   
    ?>


   $("#centro").change(function(){
        var id = $("#centro").val();
        $.ajax({
            url: 'insertManager.php',
            method: 'POST',
            data: 
            {'cd': id}
        }).done(function(manager){

            $('#manager').empty();
            console.log(manager);
            manager = JSON.parse(manager);
            manager.forEach(function(managers){
            $('#manager').append('<option value = "' +
 managers.id + '">' + managers.name + '</option>')

            })

        })
    });

And, just to make sure, that is part of the JSON he is generating

{
        "ID": "RXA47",
        "name": "Abraao Silva Souza"
    } {
        "ID": "F7R53",
        "name": "Adao David Bueno"
    } {
        "ID": "DP800",
        "name": "Adilson Silva"
    } {
        "ID": "C355P",
        "name": "Adolfo Filho"
    }

I need to be able to iterate through this JSON so I can append the options, but it doesn't even get to that, since it gives me the JSON syntax error, what am I doing wrong?

  • 写回答

1条回答

  • douwen2072 2019-08-08 18:50
    关注

    Try this code in code object array pass in one single array and after then array pass in json encode.

     <?php 
       require_once '../../DAO/model.php';$cd = $_POST['cd']; 
       $array[]=" ";
      $query = "SELECT ID,name FROM user WHERE cost_center = '$cd' order by name";
       $results = mysqli_query($conn, $query); 
        while ($row = mysqli_fetch_object($results))
        { 
            $array[]=$row;
          } 
        echo json_encode($array);
        ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog