前后端交互代码
时间: 2023-07-01 13:27:55 浏览: 49
这里给您提供一个简单的前后端交互代码,前端使用 jQuery 进行 AJAX 请求,后端使用 PHP 处理请求并返回 JSON 格式的数据。
前端代码:
```javascript
$.ajax({
url: "backend.php",
type: "POST",
dataType: "json",
data: {
action: "get_orders",
status: "pending"
},
success: function(response) {
// 处理返回的数据
},
error: function(xhr, status, error) {
// 处理请求失败的情况
}
});
```
后端代码:
```php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$action = $_POST['action'];
if ($action == 'get_orders') {
$status = $_POST['status'];
// 处理获取订单的逻辑,返回 JSON 格式的数据
$orders = array(
array('id' => 1, 'customer' => '张三', 'status' => 'pending'),
array('id' => 2, 'customer' => '李四', 'status' => 'pending'),
array('id' => 3, 'customer' => '王五', 'status' => 'completed'),
array('id' => 4, 'customer' => '赵六', 'status' => 'completed')
);
$result = array();
foreach ($orders as $order) {
if ($order['status'] == $status) {
$result[] = $order;
}
}
header('Content-Type: application/json');
echo json_encode($result);
}
}
?>
```
这段代码可以处理前端传递过来的 action 和 status 参数,根据参数的值处理不同的逻辑并返回 JSON 格式的数据。在实际的项目中,您需要根据具体的业务需求编写不同的前后端交互代码。