【问题标题】:Unable to retrieve json data using jquery无法使用 jquery 检索 json 数据
【发布时间】:2011-03-09 23:28:54
【问题描述】:

我是一个新手,一直在检索 json 数据。

以下是我的 index.php :

<script type="text/javascript" src="jquery-1.3.2.min_2.js"> 
$("document").ready(function() {

    $.getJSON("data.php",function(jsondata){
    $("#content").html(jsondata[0].content);    

    });
});
</script>
</head>
<body>
<div id="content"></div>
<div class="lg"></div>
</body>

在我的 data.php 中,我使用标准的编码和发送数据方式:

// execute query 
        $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 
         $row = mysql_fetch_row($result);
         $jsonserver[$i] = $row;
    }
    echo json_encode($jsonserver); 
    header('Content-type: application/json');
    mysql_free_result($result); 
    // close connection 
    mysql_close($con);  

我正在使用 mysql 数据库。 当我打开 localhost/data.php 时,json 数据会显示在浏览器上。 但是如果我打开 localhost/index.php 我没有得到任何想要的输出。 请解释。 谢谢!

【问题讨论】:

  • json_encode($jsondata) 输出什么?
  • 这是index.php的完整代码吗?你有 id="content" 的元素吗?
  • Uncaught ReferenceError: manifest is not defined 这是我在执行 data.php 时在 chrome 按 ctrl+shift+i 时遇到的错误,但是 firebug 在 firefox 中没有显示任何此类内容。
  • 您应该在内容之前发送响应标头。还要确保 PHP 文件在 &lt;?php 开始标记之前没有任何字符或空格,因为这将导致 PHP 发送默认标头,最常见的是:Content-type: text/html

标签: php jquery json getjson


【解决方案1】:

您需要将所有标题放在页面上的任何“回显”之前

所以:

header('Content-type: application/json');
echo json_encode($jsonserver); 

【讨论】:

  • 感谢您的努力,您的建议似乎不起作用。
【解决方案2】:

嘿, 你没有正确关闭 script 标签

试试

<script type="text/javascript" src="jquery-1.3.2.min_2.js"></script>
<script type="text/javascript">
$("document").ready(function() {
  $.getJSON("data.php",function(jsondata){
        $("#content").html(jsondata[0].content);
    });
});
</script>

【讨论】:

  • 也可以使用console.log(jsondata)进行调试
  • 很好的观察,我仍然觉得问题出在 data.php 中。 chrome 检查器给出以下错误:Uncaught ReferenceError: manifest is not defined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
  • 2013-01-06
  • 2013-01-06
  • 2016-06-06
  • 1970-01-01
  • 2021-01-25
相关资源
最近更新 更多