Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript:解码PHP json_编码响应_Javascript_Php_Json - Fatal编程技术网

JavaScript:解码PHP json_编码响应

JavaScript:解码PHP json_编码响应,javascript,php,json,Javascript,Php,Json,例如,我正在对数组进行json_编码并输出它: $key = $this->key; $sql = "SELECT * FROM Requests"; $result = $this->db->query($sql); $temp = array(); foreach($result

例如,我正在对数组进行json_编码并输出它:

$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这样有效

编辑:我尝试添加标题“Content-Type:application/json”;但这给我留下了一个错误:

TypeError:数据为空

提前谢谢

$获得'http://www.syncsapi.x10host.com/API/Public/', { 开始:“示例” } $获得'http://www.syncsapi.x10host.com/API/Public/', { 显示:“5” } .donefunctiondata{ 控制台日志数据[0]; }; };
因此,脚本的问题在于,您基本上发出了如下内容:

[
  {
    "song"   : "...",
    "artist" : "..."
  }
]
{
  "song"   : "...",
  "artist" : "..."
}
但是,您的javascript代码期望如下所示:

[
  {
    "song"   : "...",
    "artist" : "..."
  }
]
{
  "song"   : "...",
  "artist" : "..."
}
如果您打算只为该PHP服务发回一首歌曲,那么应该修改PHP服务以删除顶级数组

但是,如果您打算发回超过1首歌曲,那么您返回的数据是有意义的,但是您的javascript没有。要修复javascript,您只需更改:

alert(data['artist']);
进入:


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

该返回的可能重复:TypeError:data现在为null您可以共享该php脚本的确切输出吗?这是确切的输出,但当我进行echo测试时;这是因为数据被设置为test:/just,当我回显json_编码的或数组时,当Web服务器发出数据时,PHP脚本的输出中的数据是未定义的或为空的。不是javascript的输出。使用下面提到的标题:error-TypeError:data为null,没有它:error-data[0]未定义:/@KyleE4K我想您的php脚本可能仍然有问题。是否可以发送url以便我查看?$.get'http://www.syncsapi.x10host.com/API/Public/“,{display:'5'}.donefunctiondata{console.logdata[0];alertdata[0].artist;};令人惊叹的有趣的是,你的PHP脚本什么都不发出!空字符串。只需在浏览器中打开即可验证。