前端代码:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>商品购买</title>
</head>
<body>
	<h1>商品购买</h1>
	<form id="product-form">
		<label for="product-name">商品名称:</label>
		<input type="text" id="product-name" name="product_name">
		<br><br>
		<label for="product-quantity">商品数量:</label>
		<input type="number" id="product-quantity" name="product_quantity" min="1">
		<br><br>
		<label for="product-price">商品单价:</label>
		<input type="number" id="product-price" name="product_price" min="0" step="0.01">
		<br><br>
		<label for="total-price">商品总价:</label>
		<input type="text" id="total-price" name="total_price" readonly>
		<br><br>
		<button type="submit">购买</button>
	</form>

	<script>
		const form = document.getElementById('product-form');
		form.addEventListener('submit', (event) => {
			event.preventDefault();

			const name = document.getElementById('product-name').value;
			const quantity = document.getElementById('product-quantity').value;
			const price = document.getElementById('product-price').value;
			const totalPrice = quantity * price;

			document.getElementById('total-price').value = totalPrice.toFixed(2);

			const data = {
				name: name,
				quantity: quantity,
				price: price,
				totalPrice: totalPrice
			};

			fetch('/buy-product', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify(data)
			})
			.then(response => response.json())
			.then(data => {
				alert(`购买成功!订单号:${data.orderId}`);
			})
			.catch(error => {
				alert(`购买失败!错误信息:${error}`);
			});
		});
	</script>
</body>
</html>

后端代码(使用Node.js和Express框架):

const express = require('express');
const bodyParser = require('body-parser');
const { v4: uuidv4 } = require('uuid');

const app = express();

app.use(bodyParser.json());

app.post('/buy-product', (req, res) => {
	const name = req.body.name;
	const quantity = req.body.quantity;
	const price = req.body.price;
	const totalPrice = req.body.totalPrice;
	const orderId = uuidv4();

	// TODO: 将订单信息保存到数据库或文件中

	res.status(200).json({ 'orderId': orderId });
});

app.listen(3000, () => {
	console.log('服务器启动成功!');
});

说明:

  1. 前端代码使用HTML和JavaScript编写,包括一个表单和一个提交按钮。

  2. 表单包括商品名称、商品数量、商品单价和商品总价等输入框,以及一个用于提交表单的按钮。

  3. 前端代码使用fetch函数向后端服务器发送POST请求,请求地址为/buy-product,请求的数据为一个JSON对象,包括商品名称、商品数量、商品单价和商品总价等信息。

  4. 后端代码使用Express框架编写,监听3000端口。

  5. 后端代码使用body-parser中间件解析请求的JSON数据。

  6. 后端代码在/buy-product路由上接收前端发送的POST请求,读取请求的JSON数据,并生成一个唯一的订单号。

  7. 后端代码将订单信息保存到数据库或文件中(这里的代码未实现),并返回一个JSON对象,包括生成的订单号。

  8. 前端代码在收到后端返回的响应后,弹出一个提示框,显示购买成功或失败的信息

实现商品购买的前端后端代码

原文地址: https://www.cveoy.top/t/topic/dYaL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录