gpt4 book ai didi

php - 如何将 JavaScript 变量传递给 PHP?

转载 作者:行者123 更新时间:2023-11-29 18:15:37 26 4
gpt4 key购买 nike

我想使用表单中的隐藏输入将 JavaScript 变量传递给 PHP。

但我无法将 $_POST['hidden1'] 的值获取到 $salarieid 中。有什么问题吗?

这是代码:

<script type="text/javascript">
// View what the user has chosen
function func_load3(name) {
var oForm = document.forms["myform"];
var oSelectBox = oForm.select3;
var iChoice = oSelectBox.selectedIndex;
//alert("You have chosen: " + oSelectBox.options[iChoice].text);
//document.write(oSelectBox.options[iChoice].text);
var sa = oSelectBox.options[iChoice].text;
document.getElementById("hidden1").value = sa;
}
</script>

<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
<input type="hidden" name="hidden1" id="hidden1" />
</form>

<?php
$salarieid = $_POST['hidden1'];
$query = "select * from salarie where salarieid = ".$salarieid;
echo $query;
$result = mysql_query($query);
?>

<table>
Code for displaying the query result.
</table>

最佳答案

您无法将变量值从当前页面 JavaScript 代码传递到当前页面 PHP 代码...PHP 代码在服务器端运行,它不知道客户端发生了什么。

您需要使用另一种机制将变量从 HTML 表单传递到 PHP 代码,例如使用 GET 或 POST 方法提交表单。

<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>

<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>

<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>

关于php - 如何将 JavaScript 变量传递给 PHP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47053259/

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