格式化jQuery上传插件的json响应

时间:2015-05-09 19:36:22

标签: php jquery json jquery-upload-file-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);

2 个答案:

答案 0 :(得分:1)

seqlist1 = ['C', 'G', 'T', 'G', 'T', 'A', 'G', 'A', 'C', 'G', 'T', 'A', 'A', 'A', 'C', 'A', 'T', 'T', 'T', 'A', 'C', 'C', 'T', 'G', 'T', 'T', 'G', 'A', 'T', 'C', 'T', 'G', 'A', 'G', 'T', 'G', 'C', 'T', 'C', 'G', 'G', 'G', 'A', 'A', 'A', 'T', 'T', 'C', 'C', 'T', 'C', 'A', 'G', 'T', 'G', 'A', 'T', 'G', 'C', 'C', 'T', 'T', 'A', 'A', 'C', 'G', 'C', 'T', 'T', 'C', 'C', 'C', 'A', 'T', 'G', 'C', 'C', 'C', 'A', 'G', 'G', 'C', 'A', 'C', 'G', 'A', 'G', 'T', 'A', 'C', 'T', 'C', 'G', 'T', 'T', 'C', 'A', 'C', 'C', 'G', 'T', 'T', 'T', 'T', 'C', 'T', 'C', 'G', 'A', 'C', 'G', 'T', 'A', 'G', 'A', 'A', 'T', 'A', 'A', 'C', 'G', 'C', 'T', 'A', 'C', 'T', 'T', 'C', 'G', 'C', 'A', 'T', 'T', 'G', 'C', 'A', 'G', 'A', 'G', 'T', 'G', 'G', 'C', 'G', 'G', 'A', 'C', 'C', 'C', 'T', 'A', 'A', 'C', 'G', 'G', 'C', 'A', 'G', 'T', 'T', 'C', 'T']

seqlist2 = []

for index, item in enumerate(seqlist1):
    if item in seqlist1 == 'A':
        seqlist2.append('T')
    if item in seqlist1 == 'T':
        seqlist2.append('A')
    if item in seqlist1 == 'C':
        seqlist2.append('G')
    if item in seqlist1 == 'G':
        seqlist2.append('C')

print seqlist2

答案 1 :(得分:0)

$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));