1月 13, 2020 PHP
很多時我們使用 Http 回傳 JSON 到客戶應用程式時都會忽視了一點,就是告訴客戶應用程式 (多數是指 Browser 或 Http Agent) 你回傳的是 JSON 字串。

得多比較新的 Http Agent 都會有 Auto-detect 回傳的內容是什麽而去決定為回傳的結果 "加工"。例如回傳的是 JSON String,則會進行 `JSON.stringify()` 事前處理,然後才會回傳到使用者。所以如果伺服器可以告訴客戶要傳送的內容種類,就可以省去客戶分析內容的時間了 !

### Header

伺服器可以透過設定回應檔頭 (Response Header),來告訴客戶端回傳的內容是什麼格式。在 PHP 上我們可以使用 `header()` 功能來達成。

```php
// send json string
header('Content-Type: application/json');

// send json string with charset
header('Content-Type: application/json; charset=utf-8');
```

以上就是設定回應檔頭的語法,而 `Content-Type: application/json` 就是要告訴客戶程式,將會收到的東西是 `application/json`。以下是其他檔頭的例子 :

```php
// send html
header('Content-Type: text/html');

// send plain text
header('Content-Type: text/plain');

// send xml
header('Content-Type: text/xml');
```

### Chrome Developer Toolbar

以下是使用 Chrome 開發人員工具,可以看到回應檔頭的內容。

![](https://cdn.19site.net/files/e8/3e/e83eac97-273a-43be-ba8f-d3c9898cc1ff.png 'Content-type: application/json; charset=utf-8')

還可以設定內容的編碼 (charset encoding)。
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)