简体   繁体   English

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

[英]php mysql output array with json_encode to javascript produce no output

mysql produced an array and use json_encode to generated the output. mysql产生一个数组,并使用json_encode产生输出。 Javascript produce no output. JavaScript没有产生任何输出。

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 劉美玲 208.01.00旧约综览上2015级旧约综览上2015-06至2015-08刘健全102.00.00成长班2015班成长类2015-05至2015-07刘美玲

PHP script getEventJSON.php: PHP脚本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" 这是生成“ UL”并附加两个“ LI”的javascript

$(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. 欢迎您的指教。

You should use another $.each() loop: 您应该使用另一个$.each()循环:

$.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. 当在具有某些对象的数组上循环时,则在回调函数(key, val)键不是实际的key名,而是对象的索引。

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. 因此,如果要获取对象的键名,则必须再次将其循环到数组中的每个对象,现在这一次您将在回调中获得带有param key的键名。

  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 . [{},{}]在这种情况下,第一个循环将为您获取每个对象的索引,因此它将返回索引,如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. 然后,如果您在其中应用另一个循环,那么现在您将尝试循环到js对象{}在这种情况下,回调的key参数将提供每个对象中使用的实际键名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM