为 jQuery 上传插件格式化 json 响应
Formatting json response for jQuery upload Plugin
我正在使用 jQuery 上传文件插件并尝试将数据库集成到它。我需要像这样输出 json 响应正确格式:
{"files": [
{
"id": 1,
"name": "picture1.jpg"
},
{
"id": 2,
"name": "picture2.jpg"
}
]}
我现在有什么:
[
{
"id": 1,
"name": "picture1.jpg"
},
"id": 2,
"name": "picture2.jpg"
}
]
我的 php 文件看起来像这样:
$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");
foreach ($query as $row) {
$file = new stdClass();
$file->id = $row->id;
$file->name = $row->name;
array_push($files,$file);
}
header('Content-type: application/json');
echo json_encode($files);
$t = '[{"id": 1, "name": "picture1.jpg"}, {"id": 2, "name": "picture2.jpg"}]';
$t = json_decode($t, true);
$t = array("files" => $t);
echo json_encode($t);
输出:
{"files":[{"id":1,"name":"picture1.jpg"},{"id":2,"name":"picture2.jpg"}]}
或者用你的代码简单地做:
$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");
foreach ($query as $row) {
$file = new stdClass();
$file->id = $row->id;
$file->name = $row->name;
array_push($files,$file);
}
header('Content-type: application/json');
echo json_encode(array("files" => $files));
$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");
foreach ($query as $row) {
$file = new stdClass();
$file->id = $row->id;
$file->name = $row->name;
array_push($files,$file);
}
header('Content-type: application/json');
echo json_encode(array('files' => $files));
我正在使用 jQuery 上传文件插件并尝试将数据库集成到它。我需要像这样输出 json 响应正确格式:
{"files": [
{
"id": 1,
"name": "picture1.jpg"
},
{
"id": 2,
"name": "picture2.jpg"
}
]}
我现在有什么:
[
{
"id": 1,
"name": "picture1.jpg"
},
"id": 2,
"name": "picture2.jpg"
}
]
我的 php 文件看起来像这样:
$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");
foreach ($query as $row) {
$file = new stdClass();
$file->id = $row->id;
$file->name = $row->name;
array_push($files,$file);
}
header('Content-type: application/json');
echo json_encode($files);
$t = '[{"id": 1, "name": "picture1.jpg"}, {"id": 2, "name": "picture2.jpg"}]';
$t = json_decode($t, true);
$t = array("files" => $t);
echo json_encode($t);
输出:
{"files":[{"id":1,"name":"picture1.jpg"},{"id":2,"name":"picture2.jpg"}]}
或者用你的代码简单地做:
$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");
foreach ($query as $row) {
$file = new stdClass();
$file->id = $row->id;
$file->name = $row->name;
array_push($files,$file);
}
header('Content-type: application/json');
echo json_encode(array("files" => $files));
$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");
foreach ($query as $row) {
$file = new stdClass();
$file->id = $row->id;
$file->name = $row->name;
array_push($files,$file);
}
header('Content-type: application/json');
echo json_encode(array('files' => $files));