【发布时间】:2019-05-20 02:14:46
【问题描述】:
我使用一个简单的代码从一个 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" }
]'
【问题讨论】:
-
第 1 行第 1 列是什么字符?
-
就是这样
-
你能展示你的返回json的服务器端代码吗??
-
这个字符是撇号吗?
-
您可以在 php 中构建一个包含您想要的所有项目的数组,然后在其上使用 json_enocde,或者一次构建一个项目并在其上使用 json_enocde,如果您将其包含在 "[ "和"]"。
标签: javascript php ajax