JavaScript:解码 PHP json_encode响应


JavaScript: Decode a PHP json_encode response

例如,我正在json_encoding我的数组并输出它:

$key = $this->key;
                    $sql = "SELECT * FROM Requests";                   
                    $result = $this->db->query($sql);
                    $temp = array();
                    foreach($result as $r)
                    {
                        if($r['key'] == $key){
                        array_push($temp, array(
                            'song' => $r['song'],
                            'artist' => $r['artist'],
                            'by' => $r['by']
                        ));
                        }
                    }
                    $this->encoded = json_encode($temp);
                    echo $this->encoded;

然后,我向它发送GET请求:

$.get('http://www.example.com/file.php')
                .done(function(data){
                    alert(data['artist']);
                });

但是,这会发出以下警报:

定义

谁能帮我?我已经搜索了很多并尝试了很多,但似乎没有任何效果(例如,JSON.Parse)。

编辑:我尝试添加header('Content-Type: application/json');但它给我留下了这个错误:

类型错误: 数据为空

提前感谢!

$.get('http://www.syncsapi.x10host.com/API/Public/', {
  start: 'example'
})
$.get('http://www.syncsapi.x10host.com/API/Public/', {
    display: '5'
  })
  .done(function(data) {
    console.log(data[0]);
  });
});
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

所以你的脚本的问题在于你基本上发出了这样的东西:

[
  {
    "song"   : "...",
    "artist" : "..."
  }
]

但是你的javascript代码期待这样的东西:

{
  "song"   : "...",
  "artist" : "..."
}

如果你的意图是只为该PHP服务发回一首歌曲,你应该修改你的PHP服务以删除顶级数组。

但是,如果您打算发回超过 1 首歌曲,那么您返回的数据是有意义的,但您的 javascript 没有意义。要修复你的javascript,你可以简单地改变:

alert(data['artist']);

到:

alert(data[0].artist);

请注意,.artist['artist'] 是相同的,我的示例中的真正区别在于我添加了[0],它抓取了顶级数组中的第一项。