【问题标题】:json_encode and JSON.parse error: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 43 of the JSON datajson_encode 和 JSON.parse 错误:SyntaxError: JSON.parse: 在 JSON 数据的第 2 行第 43 列的 JSON 数据后出现意外的非空白字符
【发布时间】:2019-08-08 17:55:35
【问题描述】:

所以,我一直在尝试使用 json_encode 通过 JSON 将数组从 php 文件发送到脚本,但无论我做什么,我都会收到同样的错误:

SyntaxError: JSON.parse: JSON 数据第 2 行第 43 列的 JSON 数据后出现意外的非空白字符

现在,我已经使用 jsonlint 来验证通过 json_encode 接收到的 JSON,但它显示为无效。

这是我的 PHP 代码/查询:


<?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>')

            })

        })
    });

为了确保这是他生成的 JSON 的一部分

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

我需要能够遍历这个 JSON,以便我可以附加选项,但它甚至没有做到这一点,因为它给了我 JSON 语法错误,我做错了什么?

【问题讨论】:

  • 那是无效的 JSON。你不能像这样连接对象,{ } { }它需要是一个数组。 [ { }, { } ]

标签: javascript php json


【解决方案1】:

在代码对象数组中尝试此代码,传入一个数组,然后数组传入 json 编码。

 <?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);
    ?>

【讨论】:

  • 如果我这样做,控制台会给我这个错误:script.js:151:13 SyntaxError: JSON.parse: unexpected end of data at line 1 column 2 of the JSON data and I can'甚至不再打印日志了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 2023-02-08
  • 2019-12-27
  • 1970-01-01
  • 2017-04-28
  • 2015-03-04
相关资源
最近更新 更多