dqqs64238 2013-05-06 21:42
浏览 46
已采纳

在javascript中导航对象数组

Need help forming javascript objects from MySQL rows of data. I'm using IE9 and Chrome on Windows-7.

I've managed to get what I believe to be an array (of objects) in Javascript from mySQL data. I can use alerts to see the whole array, as well as one individual object, as in my code.

What I cannot do yet is navigate a particular object's properties (the column values of a particular row in the database).

What I need to do is iterate through myObjects, and use the property values in each to create some graphics. I also need to be able to retrieve each object's properties at any time going forward as well.

UPDATE: including my php located in head html object:

    <?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'
  • 写回答

2条回答 默认 最新

  • dongtao4319 2013-05-08 01:55
    关注

    This doesn't look like the right thing to do. Here's what you should be doing:

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

    Don't do json_encode() on each row.

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

    You can immediately use the output of json_encode($rows) in your script.

    Update

    As rightfully mentioned by bfavaretto, you can make this even shorter by encoding all rows in one go:

    ART.myObjects = <?php echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC)); ?>;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!