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?

duanlei2150
duanlei2150 这是无效的JSON。你不能只是连接这样的对象,{}{}它需要是一个数组。[{},{}]
大约一年之前 回复

1个回答

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);
    ?>
dongshuogai2343
dongshuogai2343 如果我这样做,控制台会给我这个错误:script.js:151:13 SyntaxError:JSON.parse:JSON数据的第1行第2列的数据意外结束,我甚至无法打印出日志
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问