weixin_33743661 2015-10-11 18:11 采纳率: 0%
浏览 5

JSON从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?

  • 写回答

1条回答 默认 最新

  • weixin_33727510 2015-10-11 18:15
    关注
    <?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

    评论

报告相同问题?

悬赏问题

  • ¥20 请问,这个视频播放软件的名称
  • ¥15 运筹优化,gurobi,python
  • ¥20 画CAD几张图片内容如下1111111111111111111111111111111111111111111
  • ¥15 基于python的电影系统推荐
  • ¥20 springmvc重定向和返回json
  • ¥15 数学建模——参会安排怎么做
  • ¥15 电脑键盘实现触摸功能
  • ¥25 matlab无法将表达式转换为双数组怎么解决?
  • ¥15 单片机汇编语言相关程序
  • ¥20 家用射频美容仪技术规格