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
資料負載來觀察它可能很有用(儘管在大多數情況下,這不是必需的)。