JSON.parse(xhr.responseText)意外的字符串错误

时间:2014-10-17 01:05:40

标签: javascript php ajax json

当我尝试解析我的xhr.responseText时,我得到了“未捕获的SyntaxError:Unexpected string”,我找到了答案,但找不到任何与我的问题直接相关的问题。我似乎明白我的xhr.responseText可能是JSONP,因为它是由回调操纵的,但这对我没有帮助,我怎么才能拥有JSON?我希望能够在我的Javascript中使用我的JSON和Google Maps API。我真的很困惑,只是想让这项工作,感谢阅读和可能的帮助。

这是我的PHP脚本。

<?php

header("Content-type: application/json; charset=utf-8");
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");

require("include/param_bd.inc");
try {
    $connBD = new PDO("mysql:host=$dbHote; dbname=$dbNom", $dbUtilisateur, $dbMotPasse, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    $connBD->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    exit("Erreur lors de la connexion à la BD :<br />\n" . $e->getMessage());
}
try {
    $reqZaps = "SELECT * FROM leszaps";
    $prepReqZaps = $connBD->prepare($reqZaps);
    $prepReqZaps->execute();
    $prepReqZaps->setFetchMode(PDO::FETCH_OBJ);
} catch (PDOException $e) {
    exit("Erreur lors de l'exécution de la requête SQL :<br />\n" . $e->getMessage() . "<br />\nREQUÊTE = " . $reqZaps);
}
if (!( $infoZaps = $prepReqZaps->fetch() ))
    $msgErreur = "Aucun Zap trouvé";
else {
    do
    {
        $id = $infoZaps->id;
        $coordinates = $infoZaps->coordinates;
        $arrondissement = $infoZaps->arrondissement;
        $numerocivil = $infoZaps->numerocivil;
        $rue = $infoZaps->rue;
        $nombatiment = $infoZaps->nombatiment;
        echo "{\n";
        echo "\t\"id\": \"$id\",\n";
        echo "\t\"coordinates\": \"$coordinates\",\n";
        echo "\t\"arrondissement\": \"$arrondissement\",\n";
        echo "\t\"numerocivil\": \"$numerocivil\",\n";
        echo "\t\"rue\": \"$rue\"\n";
        echo "\t\"nombatiment\": \"$nombatiment\"\n";
        echo "}\n";
    }
    while ($infoZaps = $prepReqZaps->fetch());

}
$prepReqZaps->closeCursor();
$connBD = null;

if ($msgErreur != "undefined" && $msgErreur != null) {
    echo "{\n";
    echo "\t\"erreur\":\n";
    echo "\t{\n";
    echo "\t\t\"message\": \"" . str_replace("\"", "\\\"", $msgErreur) . "\"\n";
    echo "\t}\n";
    echo "}\n";
}
?>

这是我的Javascript脚本

var xhr;
var donneesChargees = false;
var objReperes;
var reperes;

chargerKml();

function chargerKml() {

    var lienDocChargement = './script_load_kml_get.php';

    var erreur = false;

    chargerScriptAsync('./script_load_kml_bd.php', function(){
        console.log("Les ZAP ont été chargées dans la base de données");
    });
    if (window.XMLHttpRequest) {

        httpRequest = new XMLHttpRequest();

    } else if (window.ActiveXObject) {
        httpRequest = new
                ActiveXObject("Microsoft.XMLHTTP"); }
    try {
        xhr = new XMLHttpRequest();
    } catch (e) {
        alert('Erreur: Impossible de créer l\'objet XMLHttpRequest');
        erreur = true;
    }
    if (!erreur)
    {
        xhr.onreadystatechange = xhrCallback;
        xhr.open('GET', lienDocChargement, true);
        xhr.send(null);
    }
}

function xhrCallback()
{

    if (xhr.readyState == 4)
    {
        if (xhr.status != 200)
            alert('Erreur: La requête HTTP a échoué (code=' + xhr.status + ')');
        else
        {
                            objReperes = JSON.parse( xhr.responseText );
            creerReperes();
        }
    }
}

function creerReperes()
{

    try { 

        var strReperes;

                //$arrondissement = objReperes.$arrondissement;
        strReperes = '[' + xhr.responseText + ']';
        strReperes = strReperes.replace(/[\n\r\t]/g, '');
        strReperes = strReperes.replace(/}{/g, '}~{');
        strReperes = strReperes.split('~');     
        var coordonnees;
                var id;
        reperes = '[';
        for (var i = 0; i < strReperes.length; i++){
                         var numberPattern = /\d+/g;
                        id = strReperes[i].split(',')[0];
                        id = id.match( numberPattern );
            coordonnees = strReperes[i].split(',')[1] + ',' + strReperes[i].split(',')[2];
            coordonnees = coordonnees.replace(/"/g, '');
            coordonnees = coordonnees.replace('coordinates: ', '');
            coordonnees = coordonnees.split(',');
            reperes += '{"long": ' + coordonnees[0] + ', "lat": ' + coordonnees[1] + ', "id": ' + id + '}';
            if (i != strReperes.length - 1) {
                reperes += ', ';
            }
        }
        reperes += ']';
        reperes = JSON.parse(reperes);


    } catch (e) {
        alert('ERREUR: La réponse AJAX n\'est pas une expression JSON valide.');
        return;
    }


}

正如你在creeReperes()中看到的,我需要使用xrhresponsetext而不是使用JSON进行一些非正统的操作。

Here's an image of my error 哦,对不起,如果有些代码是法语。

1 个答案:

答案 0 :(得分:0)

if (!( $infoZaps = $prepReqZaps->fetch() ))
    $msgErreur = "Aucun Zap trouvé";
else {

    $rows = array();
    while ($infoZaps = $prepReqZaps->fetch()) {
        $rows[] = $infoZaps;
    }
    echo json_encode($rows);
}

$prepReqZaps->closeCursor();
$connBD = null;