前端 AJAX 設定 dataType: 'json',後端 PHP 多次 echo 字串,導致進入 error 回調而非 success。
$.ajax({
url: '1.php',
data: {"age": 12, "name": "zh"},
type: 'post',
dataType: 'json', // ⚠️ 關鍵:宣告期望 JSON 格式
success: function(response) { console.log(response); },
error: function(response) { console.log("錯誤", response); }
});
$postAge = $_POST['age'];
$postName = $_POST['name'];
echo $postAge; // 輸出 "12"
echo $postName; // 輸出 "zh"
// 實際回傳:12zh ❌ 非合法 JSON
dataType: 'json' 告訴瀏覽器:「我期望收到合法 JSON,請幫我解析」12zh(兩個字串直接拼接)JSON.parse("12zh") → 拋出語法錯誤error 回調$postAge = $_POST['age'];
$postName = $_POST['name'];
// 組裝關聯陣列
$result = array(
'age' => $postAge,
'name' => $postName
);
// 一次性輸出 JSON
echo json_encode($result);
// 輸出:{"age":"12","name":"zh"} ✅
// 註解或刪除 dataType 行
// dataType: 'json',
瀏覽器會智能判斷,但失去格式驗證保護。
| 函數 | 用途 | 範例 |
|---|---|---|
json_encode($var) | PHP 變數 → JSON 字串 | json_encode(['a'=>1]) → '{"a":1}' |
json_decode($json, true) | JSON 字串 → PHP 陣列 | json_decode('{"a":1}', true) → ['a'=>1] |
json_decode($json) | JSON 字串 → PHP 物件 | json_decode('{"a":1}') → stdClass Object |
錯誤觀念: json_encode($postAge) 單獨編碼每個變數再 echo,會產生多個 JSON 片段拼接,同樣非合法 JSON。
// ❌ 錯誤
function api() { return $data; }
// ✅ 正確
function api() { echo json_encode($data); }
// 或
function api() { die(json_encode($data)); }
即使修正為 JSON,若不小心 echo json_encode($a); echo json_encode($b); 會輸出 {...}{...},前端收到單一字串導致解析失敗。永遠只輸出一次完整 JSON。
PHP 預設回傳 200 OK。若需語意化狀態碼:
http_response_code(400); // 錯誤請求
http_response_code(401); // 未授權
http_response_code(500); // 伺服器錯誤
error_reporting(0) 或設定 display_errors=Off