doufu9145 2015-01-11 09:16 采纳率: 0%
浏览 66

php mysql输出数组用json_encode到javascript不产生输出

mysql produced an array and use json_encode to generated the output. Javascript produce no output.

There are two rows in the query results:

科目編號 科目 課程簡介 課程期間 課員

208.01.00 舊約綜覽上 2015 class of 舊約綜覽上 2015-06 to 2015-08 劉健全 102.00.00 成長班 2015 class of 成長班 2015-05 to 2015-07 劉美玲

PHP script getEventJSON.php:

mysqli_set_charset($bd, 'utf8_general_ci');
$result_event = mysqli_query($bd, $qry);

$json = array();


while ($r = mysqli_fetch_array($result_event)) {
    $json[] = array("active"=>trim($r['active']), "event_id"=>trim($r['event_id']));

}


echo json_encode($json);
mysqli_close($bd);

Here's the javascript to generate the "UL" and append two "LI"

$(document).ready(function () {
            /* call the php that has the php array which is json_encoded */

            $.getJSON('getEventJSON.php', function (data) {
                /* data will hold the php array as a javascript object */

                $.each(data, function (key, val) {

                    $('ul').append('<li id="' + key + '">' + val.active + ' ' + val.event_id + '</li>');
                });
            });
        });

However, there is no output in the browser. I have no clue how to make it works. Your enlightenments are most welcome.

  • 写回答

1条回答 默认 最新

  • du4629 2015-01-11 09:20
    关注

    You should use another $.each() loop:

    $.each(data, function (key, val) {
        $.each(val, function (key, elem) {
          $('ul').append('<li id="' + key + '">' + elem.active + ' ' + elem.event_id + '</li>');
        });
    });
    

    When you loop on an array which has some objects then in the callback function (key, val) key is not the actual key name but the index of the object.

    So if you want to get the key name of the object then you have to loop it again to the each object in the array, now this time you get the key names with the param key in the callback.

    1. [{},{}] in this case first loop will get you the index of the each object so it will return you the index like 0, 1.
    2. Then if you apply another loop in then now you are trying to loop in to a js object {} in this case the key param of the callback will give the actual key names used in the each object.
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试