本文目录导读:

我来详细介绍 PHP 前端交互的几种方式,从基础到进阶。
基础表单提交(传统方式)
GET/POST 表单提交
<!-- form.php -->
<form action="process.php" method="POST">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<button type="submit">提交</button>
</form>
<!-- process.php -->
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
// 处理数据
echo "欢迎," . htmlspecialchars($username);
}
?>
页面跳转传参
URL 参数传递
<!-- page1.php --> <a href="page2.php?id=100&name=张三">查看详情</a>
<!-- page2.php --> <?php $id = $_GET['id'] ?? 0; $name = $_GET['name'] ?? ''; echo "ID: $id, 名称: $name"; ?>
AJAX 交互(推荐)
原生 JavaScript + Fetch API
<!-- ajax.html -->
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<button onclick="loadData()">加载数据</button>
<script>
async function loadData() {
try {
const response = await fetch('api.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'action=get_users&limit=10'
});
const data = await response.json();
document.getElementById('result').innerHTML =
JSON.stringify(data, null, 2);
} catch (error) {
console.error('Error:', error);
}
}
</script>
</body>
</html>
jQuery AJAX
<!-- 使用 jQuery 简化请求 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// GET 请求
$.get('api.php', { id: 1 }, function(response) {
console.log(response);
});
// POST 请求
$.post('api.php',
{ name: '张三', age: 25 },
function(response) {
$('#result').html(response);
},
'json'
);
// 完整 AJAX 请求
$.ajax({
url: 'api.php',
type: 'POST',
data: { action: 'update' },
dataType: 'json',
success: function(data) {
console.log('成功:', data);
},
error: function(xhr, status, error) {
console.error('失败:', error);
}
});
</script>
PHP API 端
<!-- api.php -->
<?php
header('Content-Type: application/json');
// 接收 JSON 数据
$json = file_get_contents('php://input');
$data = json_decode($json, true);
// 或接收表单数据
$action = $_POST['action'] ?? $_GET['action'] ?? '';
$response = ['status' => 'success', 'data' => []];
try {
switch ($action) {
case 'get_users':
$response['data'] = [
['id' => 1, 'name' => '张三'],
['id' => 2, 'name' => '李四']
];
break;
case 'update':
// 处理更新逻辑
$response['message'] = '更新成功';
break;
default:
$response = ['status' => 'error', 'message' => '未知操作'];
}
} catch (Exception $e) {
$response = ['status' => 'error', 'message' => $e->getMessage()];
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>
Session 状态保持
<!-- login.php --> <?php session_start(); // 用户登录 $_SESSION['user_id'] = 123; $_SESSION['username'] = '张三'; // 然后在其他页面读取 echo "当前用户: " . $_SESSION['username']; ?>
使用 JavaScript 模板引擎
前后端分离模式
<!-- template_demo.php -->
<?php
// 准备数据
$users = [
['name' => '张三', 'age' => 25, 'city' => '北京'],
['name' => '李四', 'age' => 30, 'city' => '上海'],
];
?>
<!DOCTYPE html>
<html>
<body>
<!-- 模板容器 -->
<div id="user-list"></div>
<!-- 模板 -->
<script type="text/template" id="user-template">
<div class="user-card">
<h3>{{name}}</h3>
<p>年龄:{{age}} 岁</p>
<p>城市:{{city}}</p>
</div>
</script>
<script>
// 将 PHP 数据转为 JavaScript
const users = <?php echo json_encode($users); ?>;
// 使用模板渲染
const template = document.getElementById('user-template').innerHTML;
users.forEach(user => {
const html = template.replace(/{{(\w+)}}/g,
(match, key) => user[key] || '');
document.getElementById('user-list').innerHTML += html;
});
</script>
</body>
</html>
安全注意事项
防止 XSS 攻击
<?php
// 输出时进行转义
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
// 使用 json_encode 时
$data = ['message' => '<script>alert("xss")</script>'];
echo json_encode($data, JSON_HEX_TAG | JSON_HEX_QUOT);
?>
CSRF 防护
<?php
session_start();
// 生成 CSRF token
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>
<!-- 在表单中加入 token -->
<form action="submit.php" method="POST">
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
<!-- 其他表单字段 -->
</form>
完整示例:实时搜索
<!-- search.php -->
<!DOCTYPE html>
<html>
<head>
<style>
.result-item { padding: 10px; border: 1px solid #ddd; }
</style>
</head>
<body>
<input type="text" id="search-input" placeholder="搜索用户...">
<div id="search-results"></div>
<script>
const input = document.getElementById('search-input');
const results = document.getElementById('search-results');
let timeout;
input.addEventListener('input', function(e) {
clearTimeout(timeout);
const keyword = e.target.value.trim();
if (!keyword) {
results.innerHTML = '';
return;
}
// 防抖处理
timeout = setTimeout(() => search(keyword), 300);
});
async function search(keyword) {
try {
const response = await fetch('search_api.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ keyword: keyword })
});
const data = await response.json();
if (data.success) {
results.innerHTML = data.data.map(user =>
`<div class="result-item">
<strong>${user.name}</strong> - ${user.email}
</div>`
).join('');
}
} catch (error) {
console.error('搜索出错:', error);
}
}
</script>
</body>
</html>
<!-- search_api.php -->
<?php
header('Content-Type: application/json');
$json = file_get_contents('php://input');
$data = json_decode($json, true);
$keyword = $data['keyword'] ?? '';
// 模拟搜索数据库
$users = [
['name' => '张三', 'email' => 'zhangsan@email.com'],
['name' => '张小明', 'email' => 'ximing@email.com'],
['name' => '李四', 'email' => 'lisi@email.com'],
];
$results = array_filter($users, function($user) use ($keyword) {
return strpos($user['name'], $keyword) !== false;
});
echo json_encode([
'success' => true,
'data' => array_values($results)
], JSON_UNESCAPED_UNICODE);
?>
最佳实践建议
- 数据格式:使用 JSON 作为主要数据交换格式
- 错误处理:始终返回统一的错误格式
- 安全防护:对输出进行转义,验证输入
- 性能优化:使用防抖节流,缓存常用数据
- 前后端分离:考虑使用 RESTful API 架构
- 版本控制:API 添加版本号便于升级
选择什么方式取决于项目需求:
- 简单项目:传统表单 + 页面跳转
- 交互丰富:AJAX + JSON API
- 大型项目:前后端完全分离 + RESTful API