JQuery.getJson未正确触发

Nic*_*oft 0 javascript php json dom

我正在尝试使用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 ");

        });
Run Code Online (Sandbox Code Playgroud)

这是我的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;
Run Code Online (Sandbox Code Playgroud)

我假设"echo"是将JSON数据"发送"到javascript的方式?

奇怪的是,在firebug中,JSON数据以两种不同的方式呈现.如果你看下面包含的截图,第二个截图有"1988"或类似的日期,而在第一个日期更完整,如"2010-12-10".第一个截图描绘了它应该是什么,这就是我试图发送它的方式,显然它在某些时候就像这样收到了.

为什么我的div-tag没有更新日期或$ .getJSON内的警报没有被触发,只有前后的警报?

替代文字

替代文字

替代文字

Fel*_*ing 6

您没有正确创建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));
Run Code Online (Sandbox Code Playgroud)