前端和后端链接代码实现
时间: 2025-03-10 11:02:40 浏览: 31
前端和后端之间的通信通常通过HTTP请求完成,最常用的方式是使用AJAX(Asynchronous JavaScript and XML)。现代Web开发中更倾向于使用Fetch API 或者 Axios 库来发送异步请求。下面将以一个简单的示例展示如何从前端JavaScript调用之前提到的Java RESTful服务,并显示结果。
### 后端准备
假设我们已经有了上一节中的Java Spring Boot应用程序作为我们的后端服务器,它提供了一些基本的CRUD功能用于管理顾客信息。我们需要确保:
1. **启动了Spring Boot应用** 并监听默认8080端口;
2. **配置好了跨域资源共享(CORS)** ,以便允许来自其他域名的请求访问该API。(如果是在本地测试并且前后端同源,则不需要额外设置)
### 前端HTML+JS部分
#### HTML文件 `index.html`
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>客户管理系统</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="styles.css"> <!-- 样式表 -->
</head>
<body>
<h1>客户列表</h1>
<input type="text" id="searchBox" placeholder="搜索..." />
<button onclick="fetchCustomers()">查询所有客户</button><br/><br/>
<ul id="customerList"></ul>
<!-- 添加新客户的表单 -->
<form onsubmit="addNewCustomer(event)">
<input type="text" id="newName" placeholder="姓名"/>
<input type="email" id="newEmail" placeholder="邮箱地址"/>
<input type="tel" id="newPhone" placeholder="电话号码"/><br/>
<button type="submit">添加客户</button>
</form>
<script src="app.js"></script>
</body>
</html>
```
#### JS 文件 `app.js` - Fetch Customers
为了从远程服务器获取数据并在页面上动态地呈现它们,我们可以编写如下的JavaScript代码片段:
```javascript
function fetchCustomers() {
const searchQuery = document.getElementById('searchBox').value;
axios.get(`http://localhost:8080/api/customers?q=${searchQuery}`)
.then(response => {
displayCustomers(response.data);
})
.catch(error => console.error('Error fetching customers:', error));
}
function displayCustomers(customers) {
let listElement = document.getElementById('customerList');
listElement.innerHTML = ''; // Clear previous items
if (!Array.isArray(customers) || !customers.length) {
listElement.appendChild(document.createTextNode("没有匹配的结果"));
return;
}
for (let customer of customers) {
let listItem = document.createElement('li');
listItem.textContent = `${customer.name} (${customer.email}, ${customer.phone})`;
// Add delete button next to each item.
var removeButton = document.createElement('button');
removeButton.innerText = '删除';
removeButton.onclick = () => deleteCustomer(customer.id);
listItem.appendChild(removeButton);
listElement.appendChild(listItem);
}
}
```
#### JS 文件 `app.js` - Add New Customer & Delete Existing One
同样也实现了向后台提交新增加的数据以及移除已有记录的功能:
```javascript
function addNewCustomer(event){
event.preventDefault();
let newName = document.getElementById('newName').value;
let newEmail = document.getElementById('newEmail').value;
let newPhone = document.getElementById('newPhone').value;
axios.post('http://localhost:8080/api/customers', {name:newName,email:newEmail,phone:newPhone})
.then(response => {
alert('成功添加新的客户!');
fetchCustomers(); // Refresh the displayed list after adding a customer
})
.catch(error => console.error('Failed to add customer:', error));
resetFormFields();
}
function deleteCustomer(id) {
axios.delete(`http://localhost:8080/api/customers/${id}`)
.then(() => {
alert('删除成功!');
fetchCustomers(); // Update UI by refetching data once deleted successfully
})
.catch(error => console.error('Delete failed:', error))
}
// Helper function to clear form fields after submission or deletion.
function resetFormFields(){
document.getElementById('newName').value='';
document.getElementById('newEmail').value='';
document.getElementById('newPhone').value='';
}
```
这个例子展示了基础的交互流程:当用户点击按钮或提交表格时,触发相应的JavaScript事件处理器;然后这些处理器会利用Axios库发起针对指定URL路径的GET、POST或DELETE HTTP请求给后端API;最后根据响应更新DOM结构以反映最新的状态变更。
请注意,在实际的应用场景里还需要做很多工作,例如输入验证、错误处理、用户体验优化等等。此外,出于安全性考量,在生产环境中应该启用HTTPS协议并采取适当的身份认证手段保护敏感接口免受未授权访问。
阅读全文
相关推荐


















