我正在尝试使用 JSON 通过 JavaScript 将动态内容获取到我的网页。有些东西不正确,我无法弄清楚它可能是什么。在 firebug 中,我可以看到 JSON 数据已按预期检索。在“DOM”下查看 Firebug 时,我正在访问的页面 URL(我创建的实际页面,而不是 JSON 数据的 URL)为红色(参见下面的屏幕截图)。这是我的 JavaScript:
$(document).ready(function() {
$('#target').click(function() {
alert("At least I',m reached ");
$.getJSON('http://localhost/timereporting/phpscriptlibrary/get_remaining_hours.php', function(data) {
document.getElementById('errorDiv').innerHTML = "Divtext";
alert("Inside getJason");
});
alert("At least I',m done ");
});
这是我的 php 文件的重要部分:
$json_string = "{\"activities\": ";
$json_string = $json_string."[";
for ( $counter = 0; $counter < $num; $counter += 1) {
$json_string = $json_string."[".mysql_result($rows,$counter,'date').", \"".mysql_result($rows,$counter,'activity_id')."\", ".mysql_result($rows,$counter,'hours')."]";
if($counter != ($num-1)){
$json_string = $json_string.", ";
}
}
$json_string = $json_string."]}";
echo $json_string;
我认为“echo”是将 JSON 数据“发送”到 JavaScript 的方式?
一件奇怪的事情是,在 firebug 中,JSON 数据以两种不同的方式呈现。如果您查看下面包含的屏幕截图,您会发现第二个屏幕截图的日期类似于“1988”或类似的日期,而第一个屏幕截图的日期更完整,例如“2010-12-10”。第一个屏幕截图描述了它应该是什么样子,这就是我尝试发送它的方式,显然在某个时候它是这样接收的。
为什么我的 div 标签没有更新日期,或者 $.getJSON 中的警报没有被触发,只有之前和之后的警报?
最佳答案
您没有正确创建 JSON 字符串。每个字符串都必须用双引号引起来。但 2010-12-10
不是,jQuery 将其计算为 2010 - 12 - 10 = 1988
。
不要手动构建字符串,请使用 json_encode
,类似:
$data = array();
while(($row = mysql_fetch_array($result))) {
$data[] = array($row['date'], intval($row['activity_id']), intval($row['hours']));
}
echo json_encode(array('activities' => $data));
关于php - JQuery.getJson 未正确触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4580344/