【问题标题】:Print specific value from JSON object with JS使用 JS 从 JSON 对象打印特定值
【发布时间】:2013-07-25 14:30:50
【问题描述】:

我是 JSON 新手。我有一个 JSON 字符串。我想访问数据并将其打印到我这样工作的 DIV:

document.getElementById("product_content").innerHTML=javascript_array[5].name;

JSON 看起来像这样:

$data[] = array(
  "id"    =>  $product->virtuemart_product_id,
  "name"  =>  $product->product_name
);

它已经被编码并且可以工作了。

如何使用 id 获取特定值来检索名称,例如:

document.getElementById("product_content").innerHTML=javascript_array["id" == 3].name;

我没有使用行号,而是说 "id" == 3 like "id" == 3

感谢您的帮助

【问题讨论】:

  • 你不能。你必须遍历你的数组并执行if(current_item.id == 3) ...之类的操作。
  • 没有“json 对象”之类的东西。有 json STRINGS,您可以将其解码为本机数据结构,例如一个 javascript 对象或数组。您不会直接操纵或处理 JSON。把它看作是一些数据在里面的盒子。除了运输之外,您不会将盒子用于任何东西。你得先把数据解包,然后直接使用。

标签: php javascript arrays json multidimensional-array


【解决方案1】:

如果你能把 PHP 改成这个,你会处于一个更好的位置

$data[$product->virtuemart_product_id] = array(
  "name"  =>  $product->product_name
);

这会将 ID 设置为键,而不是包含数组的附加元素。然后你应该可以做

javascript_array[5]

如果你也期待字符串,你应该这样做

javascript_array["a_string"]

或者

javascript_array.a_string

【讨论】:

  • 谢谢,但 id 不是递增值,它们不同...是否可以 javascript_array[13] 其中 13 是产品的 id。对不起,我对 JSON 很陌生
  • id 可以是任何东西,字符串或数字。
猜你喜欢
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
  • 2013-06-21
相关资源
最近更新 更多