【问题标题】:Null value when checking which submit button has been pressed检查按下哪个提交按钮时的空值
【发布时间】:2014-04-16 21:39:41
【问题描述】:

我已经尝试了两个小时,但仍然没有得到结果。我在“test.jsp”文件中有一些像这样的html

<input type ="submit" name="watch" value="Edit" id="edit"></input>

<input type ="submit" name="case" value="Edit" id="editt"></input>

然后我有一个表单,当按下上面的任一按钮时,会使用 jquery 弹出

<form action="servlet.jsp" method="post">
<fieldset>
  <label for="Name">Name</label>
  <input type="text" name="name" id="name" value=""><br>
  <label for="Price">Price</label>
  <input type="text" name="Price" id="price" value=""><br>
</fieldset>
</form>  

我的 JSP 包括

<% String param = request.getParameter("watch"); %>
<% String param2 = request.getParameter("case"); %>

所以基本上我有两个编辑按钮,取决于按下哪个编辑按钮,它应该预先填充表单值。现在我的表单值为“”,因为无论我按下什么按钮,我的getParameter 总是显示为空。

我已经尝试了以下代码来检查值是否为 NULL,如果它们不是,则执行某些操作等,但无论按钮如何,都返回 null

if(param !=null){
    //assign variables and populate with data x
}
//and so on

所以我的问题是,首先,我是否正确“获取”了参数。其次,如果是这样,任何想法为什么无论我按下哪个提交按钮,我都将这两个参数都设为 null。

【问题讨论】:

    标签: html forms jsp


    【解决方案1】:

    首先,输入是一个自闭合标签。这意味着你用空格后跟/&gt;而不是&lt;/input&gt;来关闭它:

    <input type="submit" name="watch" value="Edit" id="edit" />
    <input type="submit" name="case"  value="Edit" id="editt" />
    

    这可能就是问题所在。更改后,您的代码可能会很好地工作。但我会注意到,将两个按钮命名为相同的东西并赋予它们不同的值会更容易,因为您只需读取一个并打开值:

    <input type="submit" name="submit"  value="Edit X" id="edit" />
    <input type="submit" name="submit"  value="Edit Y" id="editt" />
    

    然后在servlet或其他JSP中:

    String button = request.getParameter("submit");
    if(button == null)
    {
      out.print("no form was submitted");
      return;
    }
    else if("Edit X".equals(button))
    {
      out.print("button 1 was pressed");
      return;
    }
    else if("Edit Y".equals(button))
    {
      out.print("button 2 was pressed");
      return;
    }
    

    【讨论】:

    • 对不起,回复晚了,感谢您的帮助,但是我尝试了这个,它只是一直将它作为 null...
    • 您使用的是 Ajax,不是吗?您应该在问题中指定。
    【解决方案2】:

    你的 JSP 应该是:

    <% String param = request.getParameter("edit"); %>
    <% String param2 = request.getParameter("editt"); %>
    

    【讨论】:

    • 发送的是名称,而不是 id,所以没有。
    • id 只对 Javascript 重要,即客户端代码。
    猜你喜欢
    • 2013-10-03
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多