简体   繁体   中英

JSON decode info from php

I'm getting errors decoding JSON string.

ERROR:

Uncaught SyntaxError: Unexpected token {

My php code:

<?php 

$socket = $_GET["socket"];

$bd = new PDO("mysql:host=localhost;dbname=gestao_utilizadores" , "root" , "");

$getComponentes = $bd->prepare("SELECT * FROM componentes WHERE ( Socket=:socket )");
$getComponentes->bindValue(':socket' , $socket);
$getComponentes->execute();
$resultado = $getComponentes->fetchAll();

For ($i = 0; $i < $getComponentes->rowCount() ; $i++) { 
    $componentes = json_encode(array('tipo' => $resultado[$i]["Tipo"] , 'nome' => $resultado[$i]["Nome"] , 'socket' => $resultado[$i]["Socket"]));
    echo $componentes; 
}   

?>

My Javascript code:

$.ajax({
        url: 'compatibilidades.php',
        data: { 
            socket: $("#board option:selected").attr('value') 
        },
        success: function(dadosRecebidos) {
            teste = JSON.parse(dadosRecebidos);
            alert(teste);
        }
    });

The error is on javascript or PHP?

<?php 

$socket = $_GET["socket"];

$bd = new PDO("mysql:host=localhost;dbname=gestao_utilizadores" , "root" , "");

$getComponentes = $bd->prepare("SELECT * FROM componentes WHERE ( Socket=:socket )");
$getComponentes->bindValue(':socket' , $socket);
$getComponentes->execute();
$resultado = $getComponentes->fetchAll();

$arr = array();

for ($i = 0; $i < $getComponentes->rowCount() ; $i++) { 
    $componentes = array('tipo' => $resultado[$i]["Tipo"] , 'nome' => $resultado[$i]["Nome"] , 'socket' => $resultado[$i]["Socket"]);
    array_push($arr, $componentes);
}   

echo json_encode($arr); 

?>

Output the JSON only once, otherwise you end up with an output of several JSON strings, something like

{"key1": "value1", "key2": "value2"}{"key3": "value3"}

and that's not valid JSON

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM