BMI(Body Mass Index)是身体质量指数的简称,计算公式为:体重(kg) / (身高(m) * 身高(m))。BMI计算器通常是一个简单的表单应用,接收用户输入的身高和体重,计算并显示结果。
AJAX(Asynchronous JavaScript and XML)是一种在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术。现代AJAX通常使用JSON格式而非XML。
document.getElementById('calculateBtn').addEventListener('click', function(e) {
e.preventDefault();
// 获取输入值
const height = parseFloat(document.getElementById('height').value);
const weight = parseFloat(document.getElementById('weight').value);
// 验证输入
if (isNaN(height) || isNaN(weight) || height <= 0 || weight <= 0) {
alert('请输入有效的身高和体重数值');
return;
}
// 发送AJAX请求
const xhr = new XMLHttpRequest();
xhr.open('POST', '/calculate-bmi', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
document.getElementById('result').innerHTML = `您的BMI是: ${response.bmi.toFixed(2)}`;
} catch (e) {
console.error('解析响应失败:', e);
}
} else {
console.error('请求失败:', xhr.status);
}
};
xhr.onerror = function() {
console.error('请求错误');
};
xhr.send(JSON.stringify({ height: height, weight: weight }));
});
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/calculate-bmi', (req, res) => {
const { height, weight } = req.body;
if (!height || !weight || isNaN(height) || isNaN(weight)) {
return res.status(400).json({ error: '无效的输入' });
}
const bmi = weight / Math.pow(height / 100, 2); // 假设身高以厘米为单位
res.json({ bmi: bmi });
});
app.listen(3000, () => {
console.log('服务器运行在3000端口');
});
通过以上步骤和代码示例,你应该能够诊断并修复BMI计算器在AJAX中不工作的问题。