我有点懒,只是用PHP来存储所有这些值,我应该使用Javascript来做到这一点。什么是在Javascript中执行以下操作的最佳方法?然后我会使用jQuery的.each函数来遍历它。
$accessories = array (
array('name' => 'Chrome pull out wire Basket 500 & 600 wide ', 'price' => '60'),
array('name' => 'Chrome shoe rack 2 Tier', 'price' => '95'),
array('name' => 'Chrome Shoe Rack 3 Tier', 'price' => '145'),
array('name' => 'Chrome pull out trouser rack', 'price' => '40'),
array('name' => 'Pull out tie rack', 'price' => '135'),
array('name' => 'Pull Down hanging Rail 450mm to 1190mm width', 'price' => '33.50'),
array('name' => 'Corner Hanging Rail', 'price' => '33.50')
);
答案 0 :(得分:9)
JavaScript没有关联数组,因此您必须将其构建为数组中的一系列对象。
var accessories = [
{ 'name' : 'Chrome pull out...', 'price' : 60 },
{ 'name' : 'Chrome shoe rack..', 'price' : 95 }
];
然后,您可以根据要求使用$.each
进行循环:
$.each( accessories, function(){
alert( this.name );
});
小提琴:http://jsfiddle.net/jonathansampson/HXwMc/
通过将数组传递到json_encode()
:
echo json_encode( $accessories );
答案 1 :(得分:4)
它可能看起来像这样:
var array = [
{"name": "Chrome pull out wire Basket 500 & 600 wide ", "price": "60"},
{"name": "Chrome shoe rack 2 Tier", "price": "95"},
{"name": "Chrome Shoe Rack 3 Tier", "price": "145"},
{"name": "Chrome pull out trouser rack", "price": "40"},
{"name": "Pull out tie rack", "price": "135"},
{"name": "Pull Down hanging Rail 450mm to 1190mm width", "price": "33.50"},
{"name": "Corner Hanging Rail", "price": "33.50"}
];
请注意,这是一个对象数组。 JavaScript没有关联数组,那些是对象。
答案 2 :(得分:3)
正如Jonathan所说,这是Javascript中的一系列对象。它看起来像这样
var accessories = [
{
name: 'hello',
price: 1.00,
},
{
name: 'world',
price: 2.50,
}
]