开发者

How to correctly return an array to ajax call in php?

开发者 https://www.devze.com 2023-03-29 08:36 出处:网络
ajax calls below php and expect an array of js开发者_如何学编程on to be return. I think I have the data ready but don\'t know how to return them correctly.

ajax calls below php and expect an array of js开发者_如何学编程on 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 );


you need to use json_encode php function

print json_encode($files);


echo json_encode($files) should be enough

0

精彩评论

暂无评论...
验证码 换一张
取 消