将java脚本变量传递给相同的表单操作php文件参数


Passing java-script variable to same form action php file argument

有一个带有按钮的 html 表单,我想将点击的按钮值(作为 javascript 变量 'tree' 获得)传递给与 php 脚本参数相同的表单操作。我用于获取按钮值的 JavaScript 是这样的,

<script>
function getVal(value)
  {
  var tree =value;      
  }
</script>

在形式上,

<button type="" name="btn"  value="a" onclick="getVal(this.value)">a</button> 
<button type="" name="btn"  value="b" onclick="getVal(this.value)">b</button> 
<button type="" name="btn"  value="c" onclick="getVal(this.value)">c</button>  
<input type="submit" value="Submit">

基本上,我想做这样的事情,

<form action="backend.php" **js variable as argument**  method="POST"> 

您有两个选择。第一种是将隐藏字段添加到表单中以作为POST数据发送,第二种是将其添加到操作中,这将使它成为GET变量。

选项 1:

<script>
function getVal(value)
  {
    document.getElementById('buttonValue').value =  value;
  }
</script>
<input type="hidden" name="btnValue" id="buttonValue" value=""/>

选项 2:

<script>
function getVal(value)
  {
    document.getElementById('myForm').action =  "backend.php?btnValue="+value;
  }
</script>
<form action="backend.php" id="myForm"  method="POST">

使用第一个选项,您可以使用$_POST['btnValue']获取PHP中的值,在第二个情况下,您可以使用$_GET['btnValue']