【问题标题】:Php Json Web service ErrorPHP Json Web 服务错误
【发布时间】:2013-03-04 17:48:28
【问题描述】:

我在使用 php 创建的 JSON Web 服务时遇到问题。当我包含 echo $_GET['jsoncallback'].'('.json_encode($posts).')';除此之外,我在行(某个数字)上收到了一个错误的未识别索引,但它是 echo $_GET['jsoncallback'].'('.json_encode($posts).')';出现。

如果我离开那行,我会得到 JSON,但最终会出现标签无效的错误

我该如何解决这个问题?我的代码如下。

<?php
$link = mysql_connect('localhost','root','') or die('Cannot connect to the DB');
mysql_select_db('music_db',$link) or die('Cannot select the DB');

/* grab the posts from the db */
$query = "SELECT track.track_id, track.track_name, artist.artist_name, genre.genre_name FROM artist INNER JOIN (genre INNER JOIN track ON genre.genre_id = track.genre_id) ON artist.artist_id = track.artist_id";
$result = mysql_query($query,$link) or die('Errant query:  '.$query);

/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
  $posts[] = array('post'=>$post);
 }
}

/* output in necessary format */
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
@mysql_close($link);
?>

【问题讨论】:

    标签: php json


    【解决方案1】:

    您收到通知是因为您尝试使用的索引未设置。您需要在使用前检查它。

    if(isset($_GET['jsoncallback'])) {
      // Code here
    }
    

    【讨论】:

    • 你在输出这个$_GET['jsoncallback'].'('.json_encode($posts).')';之前使用检查如果它没有设置,那么你回退到直接输出json。
    • 所以你说要这样做if(isset($_GET['jsoncallback'])) { $_GET['jsoncallback'].'('.json_encode($posts).')'; } else { what do I put here then? }
    • 您将回显 json 输出,而无需尝试预先添加回调函数。
    • 好吧,我不知道你的意思是什么,你能举个例子吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多