如何正确返回数组在PHP Ajax调用? [英] How to correctly return an array to ajax call in php?
问题描述
Ajax调用下面PHP和期待JSON数组是回报。我觉得我有数据准备好,但不知道如何正确地回报他们。
$文件=阵列();
的foreach($ db2_databaselist为$ DB){ $文件=新stdClass的();
$文件 - >数据=日期('Y-M-D - H:I:S'的strtotime($分贝));
$文件 - > attr指示=新stdClass的();
$文件 - > attr->相对=文件;
$文件 - > attr-方式>时间戳= $ DB $类型[0]; $文件[] = json_en code($文件);
}
回声< pre>产量。的print_r($文件,TRUE)。 < / pre>中;
回声< BR>< BR>< BR>中;
的print_r($文件,TRUE);
其中,的print_r($文件,TRUE)
给我
输出=阵列
(
[0] => {数据:2011-08-07--02:30:05,ATTR:{相对:文件,时间戳:20110807023005瓦特}}
[1] => {数据:2011-07-31--02:30:09,ATTR:{相对:文件,时间戳:20110731023009瓦特}}
[2] => {数据:2011-07-24--02:30:09,ATTR:{相对:文件,时间戳:20110724023009瓦特}}
)
但的print_r($文件,TRUE)
返回任何内容。
我怎样才能让PHP返回
[
{数据:2011-08-07--02:30:05,ATTR:{相对:文件,时间戳:20110807023005瓦特}},
{数据:2011-07-31--02:30:09,ATTR:{相对:文件,时间戳:20110731023009瓦特}},
[2] => {数据:2011-07-24--02:30:09,ATTR:{相对:文件,时间戳:20110724023009瓦特}}
]
您不需要JSON EN code作为东西都是循环之后。您需要的的 破灭
。您的数组值已经是JSON字符串,这意味着使用json_en code只会逃避串!
相反:
回声'['.implode('',$文件)。']';
OR!你可以跳过json_en code在这条线:
$文件[] = json_en code($文件);
和循环的末尾是这样,而不是:
$文件[] = $文件;
}$文件= json_en code($文件);
ajax calls below php and expect an array of json to be return. I think I have the data ready but don't know how to return them correctly.
$files = array();
foreach($db2_databaselist as $db) {
$file = new stdClass();
$file->data = date('Y-m-d--H:i:s',strtotime($db));
$file->attr = new stdClass();
$file->attr->rel = "file";
$file->attr->timestamp = $db.$type[0];
$files[] = json_encode($file);
}
echo "<pre>Output = " . print_r($files,TRUE) . "</pre>";
echo "<BR><BR><BR>";
print_r($files, TRUE);
where print_r($files,TRUE)
gives me
Output = Array
(
[0] => {"data":"2011-08-07--02:30:05","attr":{"rel":"file","timestamp":"20110807023005w"}}
[1] => {"data":"2011-07-31--02:30:09","attr":{"rel":"file","timestamp":"20110731023009w"}}
[2] => {"data":"2011-07-24--02:30:09","attr":{"rel":"file","timestamp":"20110724023009w"}}
)
But print_r($files,TRUE)
returns nothing.
How can I get php to return
[
{"data":"2011-08-07--02:30:05","attr":{"rel":"file","timestamp":"20110807023005w"}},
{"data":"2011-07-31--02:30:09","attr":{"rel":"file","timestamp":"20110731023009w"}},
[2] => {"data":"2011-07-24--02:30:09","attr":{"rel":"file","timestamp":"20110724023009w"}}
]
You don't need json encode after the loop as things are. You need implode
. Your array values are already JSON strings, which means that using json_encode will only escape the strings!
Instead:
echo '['.implode(',',$files).']';
OR! You could skip json_encode on this line:
$files[] = json_encode($file);
And the end of the loop would look like this instead:
$files[] = $file;
}
$files = json_encode( $files );
这篇关于如何正确返回数组在PHP Ajax调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!