javascript - 检查是否单击了按钮...不起作用

标签 javascript php html button isset

只是对我的代码的一部分的作用进行非常简短的解释:

  • 我有两个按钮可以执行不同的操作。
  • 其中之一允许用户在表/数据库中搜索他/她想要搜索的内容
  • 另一个允许用户将内容插入数据库

我正在尝试做什么: 我试图检查用户单击了哪个按钮,以便执行适当的代码。

我环顾四周,几乎无论我走到哪里,人们都建议使用 isset(),但它对我不起作用。也许我不完全理解 isset() 的作用,但它基本上不是检查变量是否已设置吗?

这是我的代码:

<script>
    function show(x, y){
      
        <!-- Do something -->
      
    }
</script>


<form>
    <button name = "sButton" type = "button" onclick = 'show("searchForm", "insertForm");'>Perform Search</button>
    <button name = "iButton" type = "button" onclick = 'show("insertForm", "searchForm");'>Insert Data</button>
</form>


<form id = "searchForm" value "search" style = "display: none;" action = "test2.php" method = "post">

    <!-- Do something -->
  
</form>

<form id = "insertForm" style = "display: none;" action = "test2.php" method = "post">

    <!-- Do something -->
  
</form>

<!-- This is the test2.php page -->

if(isset($_POST['sButton'])){
			
    <!-- Do something -->

}
else{
			
    <!-- Do something -->

}

为了测试它,我让 if 语句打印“已检查”,而 else 打印“未检查”。当我运行代码时,它打印“未检查”。我做错了什么以及我应该做什么?

提前致谢!

最佳答案

您没有将按钮 sButtoniButton 传递到 test2.php 中,因为您的第二个和第三个表单没有它们作为输入。仅提交每个特定表单内的输入。并且您的带有按钮的表单没有任何操作,只有按钮调用 JS 函数。

我建议您为提交到 test2.php 的每个表单添加隐藏字段,如下所示:

<form id = "searchForm" value "search" style = "display: none;" action = "test2.php" method = "post">
     <input  type="hidden" name = "sButton" value="sButton" />
    <!-- Do something -->

</form>

<form id = "insertForm" style = "display: none;" action = "test2.php" method = "post">
    <input  type="hidden" name = "iButton" value="iButton" />
    <!-- Do something -->

</form>

这样你的 test2.php 应该可以工作。

关于javascript - 检查是否单击了按钮...不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29872986/

相关文章:

javascript - 告诉 VSCode 忽略可能未初始化的 Typescript 类属性值

javascript - Bottlepy - 如何从 javascript 访问 Bottle 参数 {{var}}?

javascript - JS : Assign variable value inside for loop depending on condition

php - 使用php捕获某些字符

php - Twilio 从网站向多个用户发送短信

php - ffmpeg:在 php 中以原始方向生成视频的缩略图

javascript - 获取 contenteditable 中发生 keydown 的元素

javascript - 数据属性上的 Json

html - CSS 文本对齐中心不起作用

javascript - 如何使用 redux 为处于某种状态的数组提供唯一 ID