在 JavaScript 中导航对象数组


navigating an array of objects in javascript

需要帮助从MySQL数据行形成javascript对象。我在Windows-7上使用IE9Chrome

我已经设法从mySQL数据中获得了我认为是Javascript中的(对象(数组。我可以使用警报来查看整个数组以及一个单独的对象,就像在我的代码中一样。

我还不能做的是导航特定对象的属性(数据库中特定行的列值(。

我需要做的是循环访问myObjects,并使用每个属性值来创建一些图形。我还需要能够随时检索每个对象的属性。

更新:包括我位于head html对象中的php:

    <?php
    //------------------- constants --------------------
    $objects = array();
    $jsonData = "";
    //------------------- database connection ----------
    $data_source = 'mysql:host=localhost;dbname=myDB';
    $db_user = 'root';
    $db_password = 'password';
    $conn = new PDO($data_source, $db_user, $db_password,
              array(PDO::ATTR_EMULATE_PREPARES => false,
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_PERSISTENT));
    //prepare query
    $stmt = $conn->prepare("SELECT * FROM tblbranchstatus");
    $stmt->execute();
    //fetch each row of results
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $rows[] = json_encode($row);
    }
?>
var ART = {};
//capture data from database as json string data
ART.strJSON = <? php echo json_encode($rows); ?> ;
//capture json string data as array of javascript objects
//using 'eval' cause I know this data's source and I couldn't get JSON.parse to work
ART.myObjects = eval(ART.strJSON);
ART.branch = ART.myObjects[6];
alert(ART.branch); // this gives me the expected object {"a":"aa", "b":"bb"...}
alert(ART.branch.a); // can't retrieve the property - gives me 'undefined'

这看起来不是正确的做法。以下是您应该做的:

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $rows[] = $row;
}

不要对每一行都执行json_encode()

ART.myObjects = <?php echo json_encode($rows); ?>;

您可以立即在脚本中使用json_encode($rows)的输出。

更新

正如 bfavaretto 正确提到的,您可以通过一次性编码所有行来使其更短:

ART.myObjects = <?php echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC)); ?>;

我会检查ART.branch是否真的是一个带有JSON表示法的字符串,而不是实际的对象。