SyntaxError:JSON.parse:解析PHP输出时出现意外字符


SyntaxError: JSON.parse: unexpected character when parsing output from PHP

My php返回如下内容:

  if(!$result = $db->query($sql)){
    echo $db->error;
      die('There was an error running the query [' . $db->error . ']');
  }
  echo 'Total results: ' . $result->num_rows . "'n";
  while($row = $result->fetch_assoc()){
      echo json_encode($row);
      echo "'n";
  }

在我的javascript中,如果是json对象,我想把输出放在页面上,如果是其他对象,我只想把它记录到控制台:

var divOutput = function(output) {
  try {
    // var x = output.trim();
    // x = JSON.parse(JSON.stringify(x));
    var x = JSON.parse(output);
    console.log(x);
    $("#dbOut").html(JSON.stringify(x, null, ''t'));
  } catch (e) {
    console.log(output);
    console.log(e);
  }
}
var getPlayerByID = function() {
  var myNumber = document.getElementById("PlayerInput").value;
  $.ajax({
    url : "db_funcs.php",
    data : {
      action : 'getPlayerByID',
      a : myNumber,
    },
    type : 'post',
    success : function(output) {
      divOutput(output);
    }

然而,当我查询数据库时,它抛出了JSON解析错误。我该怎么做?})}

JSON必须作为SINGLE单片JSON字符串输出。您正在构建多个SEPARATE json字符串,这是非法语法。

将JSON视为相当于javascript变量赋值的右侧:

var foo = this_part_is_json;

例如,你需要

var foo = [[stuff from row 1], [stuff from row2], etc...];

但正在生产

var foo = [stuff from row1][stuff from row2];
                           ^---syntax error would occur here

你需要

$arr = array();
while($row = fetch from db) {
   $arr[] = $row;
}
echo json_encode($arr);

它抛出错误,因为您不是在回显json。

在线

echo 'Total results: ' . $result->num_rows . "'n"

您已经回显了一些不是json编码的内容。有了这个代码,它应该可以工作:

//echo 'Total results: ' . $result->num_rows . "'n";  <---- this is not json
$arr = [];
while($row = $result->fetch_assoc()){
     $arr[] = $row; //save each row in array
    //echo "'n";
}
echo json_encode($arr); //encode all data as json

如果您想要json输出中的行数,请使用类似的键将其添加到$arr

$arr["num_rows"] = $result->num_rows;

这是错误的

while($row = $result->fetch_assoc()){
  echo json_encode($row);
  echo "'n";
}

试试这个

$arr = array();
while($row = $result->fetch_assoc()){
  $arr[] = ($row);
}
echo json_encode($arr);

只使用json_encode()一次,使用数组在while() 中存储值