PHP实现前后端分离
作者:野牛程序员:2023-11-14 10:02:35php阅读 2913
前后端分离是一种架构设计方式,其中前端和后端是独立的系统,彼此通过 API 进行通信。PHP 可以用于构建后端服务,提供 API 给前端使用。以下是一个简单的 PHP 前后端分离的示例:
后端 PHP 代码:
<?php
header('Content-Type: application/json');
// 处理前端请求
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// 处理 GET 请求
$data = array('message' => 'Hello from the server!');
echo json_encode($data);
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 处理 POST 请求
$requestData = json_decode(file_get_contents('php://input'), true);
$response = array('message' => 'Received data: ' . json_encode($requestData));
echo json_encode($response);
} else {
// 其他请求方法返回错误
http_response_code(405);
echo json_encode(array('error' => 'Method Not Allowed'));
}
?>此 PHP 后端简单地处理了 GET 和 POST 请求,并返回相应的 JSON 数据。
前端 HTML + JavaScript 代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frontend</title>
</head>
<body>
<div id="result"></div>
<script>
// 发送 GET 请求
fetch('http://your-backend-url/api.php', {
method: 'GET',
})
.then(response => response.json())
.then(data => {
document.getElementById('result').innerText = 'Response from server: ' + data.message;
})
.catch(error => console.error('Error:', error));
// 发送 POST 请求
fetch('http://your-backend-url/api.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key: 'value' }),
})
.then(response => response.json())
.then(data => {
document.getElementById('result').innerText = 'Response from server: ' + data.message;
})
.catch(error => console.error('Error:', error));
</script>
</body>
</html>请确保将 http://your-backend-url/api.php 替换为实际的后端 API 地址。这只是一个简单的例子,实际中可能需要更复杂的路由、身份验证和错误处理。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:PHP将MySQL中数据导入表单
- 下一篇:用turtle绘制叠加等边三角形
