使用$.getJSON
,我得到了一个非常大的结果,其中包含我们每个产品的元素。我需要使用变量访问一些属性,但无法设法找出jQuery语法。
$.getJSON("datasource.php",function(licensed){
// Hardcoded works
alert ( licensed.product5200.order_id );
// How to use a variable instead, something like this:
var MyVar = "product5200";
alert ( licensed.MyVar.order_id );
});
编辑:在我开始使用之前,有没有办法确定“product5200”是否存在?
console.info('Is It There?:' + licensed['product5200'].hasOwnProperty);
答案:console.info('Is It There?:' + licensed.hasOwnProperty('product5200'));
JSON对象(为了清晰起见显示为PHP数组)
[licensed] => Array
(
[product5200] => Array
(
[product_id] => 5200
[order_id] => 159004882
)
[product5204] => Array
(
[product_id] => 5204
[order_id] => 159004882
)
答案 0 :(得分:4)
您也可以在对象上使用数组访问表示法。
licensed[MyVar].order_id
应该有用。
顺便说一句,我建议console.log
优先于alert
,特别是在Chrome中(可让您检查已记录对象的内容)。