P粉5390555262023-10-10 09:38:23
返回 JSON 的完整且清晰的 PHP 代码是:
$option = $_GET['option']; if ( $option == 1 ) { $data = [ 'a', 'b', 'c' ]; // will encode to JSON array: ["a","b","c"] // accessed as example in JavaScript like: result[1] (returns "b") } else { $data = [ 'name' => 'God', 'age' => -1 ]; // will encode to JSON object: {"name":"God","age":-1} // accessed as example in JavaScript like: result.name or result['name'] (returns "God") } header('Content-type: application/json'); echo json_encode( $data );
P粉3115638232023-10-10 00:45:19
虽然通常没有它也没什么问题,但您可以而且应该设置 Content-Type
标头:
<?php $data = /** whatever you're serializing **/; header('Content-Type: application/json; charset=utf-8'); echo json_encode($data);
如果我不使用特定的框架,我通常允许一些请求参数来修改输出行为。通常对于快速故障排除来说,不发送标头,或者有时 print_r
数据负载来观察它可能很有用(尽管在大多数情况下,这不是必需的)。