即时使用ajax使用php检索数据库数据并将其转换为json
<?php
echo json_encode($data);
?>
ajax功能
ajaxCall("getdata.php", container, function (data) {
var count = data.length
var i;
var array[];
for (i = 0; i < count; i++) {
container.innerHTML += data[i].property; //this is doing well
array[i] = data[i].property; //this when goes wrong;
}
});
当我尝试重新计算array[i]
其未定义的返回时,我做错了什么?
答案 0 :(得分:0)
JavaScript中的数组初始化应该类似于 var array = [];
ajaxCall("getdata.php", container, function (data) {
var count = data.length
var i;
var array = [];
for (i = 0; i < count; i++) {
container.innerHTML += data[i].property; //this is doing well
array[i] = data[i].property; //this when goes wrong;
}
});
或者您可以使用 for...in
循环进行迭代,并使用 push()
为数组添加值
ajaxCall("getdata.php", container, function (data) {
var array = [];
for (var v in data) {
container.innerHTML += v.property; //this is doing well
array.push(v.property); //this when goes wrong;
}
});
答案 1 :(得分:0)
使用JSON.parse。
演示:
var json = '[{"result":"OK","count":1}, {"result":"NOK","count":2}]',
obj = JSON.parse(json);
alert(obj[0].result);
alert(obj[1].result);
alert(obj[0].count);
alert(obj[1].count);
所以在你的情况下,它看起来像这样:
ajaxCall("getdata.php", container, function (data) {
array = JSON.parse(data);
});