您引用的特定错误(JSON.parse: unexpected non-whitespace character after JSON data)是 Javascript 对其进行解码时。
json_encode
从混合值参数返回一个字符串。json_encode 文档
您要么需要echo
输出结果,要么将其添加到另一个变量以稍后输出。例如。
while ($row = $res->fetchRow()){
$resGold = $row['gold'];
$resSilver = $row['silver'];
$resBronze = $row['bronze'];
$resGdp = $row['gdp'];
$resPopulation = $row['population'];
$resCountry = $row['country_name'];
$gold_score = ($resGold * $gold_value);
$silver_score = ($resSilver * $silver_value);
$bronze_score = ($resBronze * $bronze_value);
$score_pop = (($gold_score + $silver_score + $bronze_score)/$resPopulation);
$score_gdp = (($gold_score + $silver_score + $bronze_score)/$resGdp);
if($population == 'true'){
$result = $res->fetchRow();
$result['score'] = "$score_pop";
echo json_encode($result);
}
else if($gdp == 'true'){
$result = $res->fetchRow();
$result['score'] = "$score_gdp";
echo json_encode($result);
}
}
if($population == 'false' && $gdp == 'false'){
echo "Please select either population or gdp from view.htm";
}
如果您尝试对多行进行编码并将它们全部返回,则最好将其添加$result
到数组中并在while
循环外对其进行编码,就像您不这样做一样,您的 JSON 字符串可能如下所示:
{gold:123,silver:456,bronze:789}{gold:987,silver:654,bronze:321}
这不是有效的 JSON,因为它一次只能解析一个对象或数组。下面是一个有效的 JSON 字符串
[{gold:123,silver:456,bronze:789},{gold:987,silver:654,bronze:321}]
这是您的数据的数组表示,并将解析为您的 JSON 编码对象列表。这是您在回显之前使用数组存储 JSON 的代码。
$results = array();
while ($row = $res->fetchRow()){
$resGold = $row['gold'];
$resSilver = $row['silver'];
$resBronze = $row['bronze'];
$resGdp = $row['gdp'];
$resPopulation = $row['population'];
$resCountry = $row['country_name'];
$gold_score = ($resGold * $gold_value);
$silver_score = ($resSilver * $silver_value);
$bronze_score = ($resBronze * $bronze_value);
$score_pop = (($gold_score + $silver_score + $bronze_score)/$resPopulation);
$score_gdp = (($gold_score + $silver_score + $bronze_score)/$resGdp);
if($population == 'true'){
$result = $res->fetchRow();
$result['score'] = "$score_pop";
array_push($results,$result);
}
else if($gdp == 'true'){
$result = $res->fetchRow();
$result['score'] = "$score_gdp";
array_push($results,$result);
}
}
if($population == 'false' && $gdp == 'false'){
echo "Please select either population or gdp from view.htm";
}
else
{
//Note: This is in the 'else' statement as echoing the JSON then that string
// will also cause errors as it ends up not being valid JSON anymore
echo json_encode($results);
}
在我上面的示例中,您正在回显有关选择人口或 GDP 的字符串,因为它不是 JSON 编码的,并且上面的部分否则会以 JSON 编码,您在尝试解码时可能会遇到解析错误。如果此 PHP 页面旨在返回 JSON 编码的数据,而您的错误消息不是 JSON 编码的,那么获取该值的任何内容都可能存在问题。