json_encode is returning undefined from Javascript
json_encode is returning undefined from Javascript
我有一个php数组,我json_encode并传递给一个javascript函数中的变量。一切看起来都很好,在Json编码之后,数组看起来像一个有效的Javascript数组,但我一直在输出上得到未定义。下面是代码的样子:
<script src="js/jquery-1.8.1.min.js"></script>
<script>
$(function() {
getPhotos();
});
function getPhotos() {
var photosArray= <?php echo json_encode($photos_array); ?>;
alert(photosArray.length);
}
在浏览器中是这样的:
function getPhotos() {
var photosArray= {"12":"1401880321163321491.png","11":"1401880200994911748.jpg","10":"1401866598206920573.png","6":"1401863850983364637.png","7":"14018645731921210607.png","8":"14018646851258457972.png","9":"14018647281804140101.png","13":"1401880485229593545.png","15":"1401933387756388853.jpg","16":"14019688951333867090.jpg","17":"14021062501374960169.jpg","18":"14021064801222019341.jpg","19":"14021065441073158757.png","20":"14021066841708486619.png","21":"1402106744569372168.png","22":"14022970452004604041.jpg","23":"1402297585941206466.jpg"};
alert(photosArray.length);
}
我做错了什么吗?
你的数组没有被用作数组,它是一个对象。JavaScript中的对象没有长度属性(除非你创建了一个)。
无论创建PHP数组的是什么,看起来都像是使用字符串作为索引。确保它们是实整数。在PHP中,这很好,因为PHP有关联数组的概念。当编码为JSON用于JavaScript时,它就变成了对象字面量。
重申一下,你不希望这样:
{"1":"1401880321163321491.png", // ...
你想要这个:
["1401880321163321491.png", // ...
只有在PHP数组中的数组索引是数字1
而不是字符串"1"
时才有可能。您还可能遇到问题,因为您的数组是"稀疏的",不能用普通数组字面量复制。
这是一个Javascript对象,而不是一个数组,因此它没有长度属性。它也是无序的
尝试alert(photosArray['11'])
查看结果
相关文章:
- 为什么会出现错误;未捕获的类型错误:undefined不是函数;
- /undefined在我的404错误日志中多次出现
- RequireJS向模块传递配置总是返回undefined
- JSON数组数据返回Undefined
- 为什么会出现错误,“UncaughtTypeError:undefined不是函数”
- Array.lenght = undefined
- mongoose.connect undefined不是一个函数
- JavaScript”;.方法“;返回undefined
- Uncaught TypeError:undefined不是函数-ember js
- Jquery - table.row(tr) is undefined
- jQuery可以't获取data-*属性值,返回undefined
- noty.js is returning undefined
- 将对象的列表c#传递给javascript:undefined变量时出错
- $routeParams is undefined
- 试图打印/调用/或提醒数组中的对象:Getting Undefined
- Validate JSON from Mongo?
- jQuery Mobile Undefined不是一个函数
- Get JSON from an url
- Javascript/JSON警报返回Undefined
- json_encode is returning undefined from Javascript