获取JSON结果

时间:2016-02-25 11:53:05

标签: javascript php json

我需要做的是从info.php文件中获取结果。

这是info.php:

<?php

$dbh = new PDO('mysql:host=localhost;dbname=csgo', 'root', '');

$sth = $dbh->query("SELECT * FROM users");

$row = $sth->fetchAll(PDO::FETCH_ASSOC);

    foreach($row as $r){
    $steamids = $r['steam_id'];

    $APIKEY = '********';
    $steamAPI = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?steamids=$steamids&key=$APIKEY&format=json";
    $json_object= file_get_contents($steamAPI);
    echo $json_object;
}

这是app.js

$(document).ready(function(){

    $.getJSON("/info.php", function(json){
       $("#userinfo").html('<img style="width: 100px; height: 100px" style="width: 100px; height: 100px" src="'+json.response.players[0].avatarfull+'">');
       $("#steamProfile").html('<a href="'+json.response.players[0].profileurl+'">STEAM nuoroda</a>');
       $("#personaname").html(json.response.players[0].personaname);
    });
});

我应该如何在app.js中正确获取?

更新

$(document).ready(function(){

    $.getJSON("/info.php", function(json){
        $.each(json.response, function(i, player){
       $("#userinfo").html('<img style="width: 100px; height: 100px" style="width: 100px; height: 100px" src="'+player.players.avatarfull+'">');
       /*$("#steamProfile").html('<a href="'+json.response.players[0].profileurl+'">STEAM nuoroda</a>');
       $("#personaname").html(json.response.players[0].personaname);*/
       });
    });
});

现在我得到Uncaught TypeError: Cannot read property 'length' of undefined

1 个答案:

答案 0 :(得分:0)

您的PHP文件将依次输出几个不相关的JSON blob,例如:

{..}{..}{..}

这使得JSON解析器无法解析。您必须解码数据并构建新的有效JSON结构:

$sth = $dbh->query("SELECT * FROM users");
$data = [];

foreach ($sth as $r) { // no need to `fetchAll`
    ...
    $json = file_get_contents($steamAPI);
    $data[] = json_decode($json);
}

echo json_encode($data);