从json_encode访问JSON对象值($ phpArray)

时间:2014-03-04 22:08:14

标签: javascript php jquery arrays json

我是JSON / Javascript新手并且遇到这种性质的问题。

在我的php脚本中我将php数组传递给javascript,如下所示:

echo '<img id="Next" src="misc/arrow_right.png" onclick="imageSlider(' . json_encode($images) . ')" >';

在我的javascript中:

function imageSlider(imagesArray) {
alert(imagesArray); 
}

上面的警告打印表单对象Object

的输出

问题是我不知道如何最好地'分解'或分解这个对象,以便我可以提取我原来json_encoded的数据。原始数组的结构是一个带字符串的简单数字索引数组,即{ {1}}等

我也试过["image1", "image2",...],我得到了这个字符串:

  

{ “1”: “images1.jpg”, “2”: “images2.jpg”, “3”: “images3.jpg”, “4”: “images4.jpg”, “5”:“images5 .JPG“}

无论哪种方式,我都不确定如何最好地在javascript中获取我的图像名称和数组索引。例如 从对象中提取1和images1.jpg或者是否有办法将'stringified'对象转换为真正的javascipt数组......? 感谢

3 个答案:

答案 0 :(得分:0)

var imgs=eval('('+imagesArray+')');

然后你可以访问imgs对象。

请记住,这不再是索引数组,而是键值存储:

for (key in imgs){
  var img=imgs[key];
  console.log(img);
}

答案 1 :(得分:0)

您可以使用着名的json2.js在Javascript中将json字符串解析为对象。包含json2.js后,您可以使用:

imageArray = JSON.parse(encodedJson);

我认为在你的例子中,如果你有一个json编码对象,它已经是一个真正的javascript对象。你可以使用

console.log(imageArray);

查看imageArray的内容。您可以访问对象的属性,如:

alert(imageArray[1]) //this will alert "image1.jpg"

但我想让你知道imageArray不是一个数组,它是一个javascript对象。如果键是一个数字(如您的示例中所示),则无法使用点表示法来达到javascript对象的值。所以你不能使用 imageArray.1 来达到“image1.jpg”,你应该使用方括号,如果你的键是上面代码的数字。如果要使用点表示法,则应创建键字符串,例如:

imageArray = { "i1": "image1.jpg", "i2": "image2.jpg" } //this way you can use imageArray.i1 to get "image1.jpg"

答案 2 :(得分:0)

你很亲密。

function imageSlider(imagesObject) {

    //access it like an Array (note the quotes around 1), no other changes needed.
    imagesObject["1"];

}
相关问题