很多時我們使用 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 開發人員工具,可以看到回應檔頭的內容。

還可以設定內容的編碼 (charset encoding)。