JavaScript 運行於瀏覽器(客戶端),PHP 運行於伺服器。兩者透過 **HTTP 請求** 互動:JS 導向帶參數的 PHP 網址,PHP 處理後輸出結果(HTML/JSON/純文字),JS 再決定如何呈現。
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>JS 呼叫 PHP 範例</title></head><body>
<script>
function func() {
if (confirm("Are you OK with this?")) {
location.href = "ok.php?action=ok";
} else {
location.href = "ok.php?action=cancel";
}
}
</script>
<a href="#" onclick="func(); return false;">請點擊這裡</a>
</body></html>
<?php
header('Content-Type: text/html; charset=utf-8');
$action = $_GET['action'] ?? '';
if ($action === 'ok') {
echo "I'm OK!";
} else {
echo "I'm not OK!";
}
?>
<script>
function callPhpAsync(action) {
fetch('ok.php?action=' + encodeURIComponent(action))
.then(r => r.text())
.then(txt => {
document.getElementById('result').textContent = txt;
});
}
</script>
<button onclick="callPhpAsync('ok')">確定</button>
<button onclick="callPhpAsync('cancel')">取消</button>
<div id="result"></div>
location.href 或 fetch()/XMLHttpRequest 發起請求。?key=val) 傳遞,PHP 用 $_GET 接收。$_SERVER['REQUEST_METHOD']。header('Content-Type: ...'),避免編碼亂碼。