gpt4 book ai didi

php - 使用隐藏表单将 javascript 变量传输到 php?

转载 作者:行者123 更新时间:2023-11-28 15:57:46 25 4
gpt4 key购买 nike

我的页面上有一个表单,要求用户输入他们的高度/体重,然后计算他们的 BMI 并将其存储在数据库中。我对如何将 javascript 变量传输到 php 变量很感兴趣。我知道我必须使用隐藏表单,但我似乎无法弄清楚它们是如何工作的。

这是我的代码

<?php include "base.php"; ?>
<?php session_start (); ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>BMI</title>
</head>

<body>

<form id="bmi" action="main.php" method="post">
<p>Enter your height(in inches):</p><input type="text" id="height box" name="height box">
<p>Enter your weight(in pounds):</p><input type="text" id="weight box" name="weight box">
<input type="hidden" id="bmi" name="bmi">
<input type="button" value="Calculate" id="calc button" name="calc button" onClick="calc()">
</input>
</form>

<script type="text/javascript">

function calc()
{
// get variables from textboxes
var height=document.getElementById('height box').value;
var weight=document.getElementById('weight box').value;
var bmi=document.getElementById('bmi').value;

// calculate BMI
weight/=2.2;
height/=39.37;
BMI=Math.round(weight/(height*height));

</script>

<?php

//insert username, date, and bmi into the db
$username = mysql_real_escape_string($_SESSION['Username']);
$date = date('Y-m-d');
$bmi = mysql_real_escape_string($_POST['bmi']);

mysql_query("INSERT INTO bmi (username, bmi, date) VALUES('".$username."', '".$bmi."', '".$date."')");

?>

</body>

</html>

base.php 就是我连接到 sql 服务器并选择数据库内容的地方

javascript bmi 变量似乎没有传输到 php $bmi 变量。我到底做错了什么?

最佳答案

将隐藏输入bmi的值设置为计算值。

<form id="bmi" action="main.php" method="post">
<p>Enter your height(in inches):</p><input type="text" id="height box" name="height box">
<p>Enter your weight(in pounds):</p><input type="text" id="weight box" name="weight box">
<input type="hidden" id="bmi" name="bmi">
<input type="submit" value="Calculate" id="calc button" name="calc button" onClick="calc()">
</form>

<script type="text/javascript">

function calc()
{
// get variables from textboxes
var height=document.getElementById('height box').value;
var weight=document.getElementById('weight box').value;
var bmi=document.getElementById('bmi').value;

// calculate BMI
weight/=2.2;
height/=39.37;
document.getElementById('bmi').value=Math.round(weight/(height*height));
}
</script>

关于php - 使用隐藏表单将 javascript 变量传输到 php?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18048425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com