开发者

How to set an Array in Javascript dynamically?

I am working on an e-commerce website. There is an array "products" in javascript defined by the following code

<script type="text/javascript">
    var products = 
    [
         {"id":"1","title":"Apple iPhone 4"},
         {"id":"2","title":"BlackBerry 9780 Bold"}
    ];
    /*some other javascript code*/
</script>

I want this array to be updated开发者_JS百科 dynamically according to the number of rows returned by querying the database. For example, suppose I query the database and 5 rows are returned. I want this array to be updated with those 5 rows. Please help me getting this done. I am using PHP, MySQL, Apache on Windows machine.


You want the push function: http://www.w3schools.com/jsref/jsref_push.asp

var products = 
[
     {"id":"1","title":"Apple iPhone 4"},
     {"id":"2","title":"BlackBerry 9780 Bold"}
];

// Let's add a new phone:
products.push({"id":"3","title":"HTC Evo"});

/*
    products now equals: 
    [
         {"id":"1","title":"Apple iPhone 4"},
         {"id":"2","title":"BlackBerry 9780 Bold"},
         {"id":"3","title":"HTC Evo"}
    ];
*/

To account for the possibility you may have an existing array and you'd like to update it via ajax, you can do this dynamically with PHP:

<script type="text/javascript">
<?php foreach($phones as $phone): ?>
    products.push({"id":"<?=$phone['id']?>","title":"<?=$phone['name']?>"});
<?php endforeach; ?>
</script>


The top answer to the question JSON encode MySQL results could achive this for you:

$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows[] = $r;
}

print json_encode($rows);

In your case, replacing the last line with

?>
var products = <?php echo json_encode($rows); ?>;
<?php

would initialize the JavaScript object with your query results. This would need to be done before the page is loaded, because the PHP runs on the server producing the JavaScript for the client. If you need to get the results after the client page is loaded you would need a more complicated solution, probably using AJAX.


I would make a server side script that makes the connection to the database, get's the products, and constructs the JSON for you, so that way all you have to do is make an AJAX request to the script from the client side and it will return everything for you for use on your webpage.


You can use PHP to output json directly into the page.

Assuming that $data is an array that contains the products you want to output.

In the template you would do something like this:

<script type="text/javascript">
var products =  <?php echo json_encode($data) ?>;
</script>


products[products.length] = {..some data..};
products.push({..some data..});

Or you need something else?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜