我使用一个简单的代码从 php 页面获取一个字符串,我多次使用该代码从 php 文件中获取字符串响应。这是我第一次尝试将此结果转换为 json 对象(或数组)。
当我在响应上使用 JSON.parse 时,我收到如下所示的错误。如果我作为 JSON.parse() 的参数传递我已控制台日志的文本(即在传递给 javascript 时从控制台复制),它可以完美地工作。
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
var result = this.responseText;
resultsObj = JSON.parse(result);
}
php代码如下:
<?php
if (!session_id()) {
@session_start();
}
header('Content-Type: text/json');
require 'controlleur/connexionDB.php';
$sql = "SELECT * FROM depart";
$result = $conn->query($sql);
$liste .= "[";
$compteur = 0;
while ($row = $result->fetch()) {
if ($compteur != 0) {
$liste .= ", ";
}
$liste .= "{ \"idDepart\" : \"$row->idDepart\", \"idCircuit\" : \"$row->idCircuit\", \"dateDebut\" : \"$row->dateDebut\", \"nbPlaces\" : \"$row->nbPlaces\", \"prix\" : \"$row->prix\", \"titrePromotion\" : \"$row->titrePromotion\", \"rabais\" : \"$row->rabais\" }";
$compteur++;
}
$liste .= "]";
$reponse = $liste;
echo $reponse;
我收到此错误:SyntaxError: JSON.parse: 第 1 行第 1 列的意外字符
控制台中变量“result”的结果是这样的:
'[
{ "idDepart" : "1", "idCircuit" : "5", "dateDebut" : "2019-06-02", "nbPlaces" : "30", "prix" : "4000", "titrePromotion" : "vfv", "rabais" : "10" },
{ "idDepart" : "2", "idCircuit" : "5", "dateDebut" : "2019-06-10", "nbPlaces" : "30", "prix" : "6000", "titrePromotion" : "ded", "rabais" : "4" },
{ "idDepart" : "3", "idCircuit" : "5", "dateDebut" : "2019-07-02", "nbPlaces" : "30", "prix" : "7000", "titrePromotion" : "ded", "rabais" : "6" }
]'
茅侃侃
BIG阳
冉冉说