JSP和带表单的JavaScript

JSP and JavaScript with form

本文关键字:JavaScript 表单 JSP      更新时间:2023-09-26

我在Registeration.jsp页面中有一个表单:

form name="users"method="post"onSubmit="return checkCorrect()"action="Registeration.jsp">

Script checkCorrect写在页面的开头,根据提交到表单的信息返回true或false(如果重要的话,使用getElementById),并且脚本肯定有效(以前在没有jsp的html页面上工作)

在表格之后我有这个:

<%if(request.getMethod().equals("POST")){…}

我需要jsp部分只有在表单成功提交后才能工作,但不知何故,javascript脚本没有被调用,也不起作用,表单总是被提交的。

我做错了什么?

编辑:
我的页面中没有重定向,javascript检查函数、表单以及提交表单后处理表单的JSP部分都在同一页面上
jsp部分用于将表单中的数据发送到数据库
功能:

函数checkCorrect(){
var fullname=document.getElementById("fullname").value

if(response.length==0)

返回true
}
其他

alert("这些问题在您的表单中找到:''n''n"+响应)
return false
}
}

然后是body和表单,然后
jsp部分:

<%

if(request.getMethod().equals("POST")){

字符串fullname=request.getParameter("fullname")
并继续..}%>

解决方案:
检查JavaScript部分真的很好的人,它没有编译器,所以即使是一个小问题也可能会把整个项目搞砸。

<% uname=""+request.getAttribute("username"); %>

只有当你加载页面或刷新页面时,这个变量才会得到一个值。

我想你的页面流程如下。

您有了表单的第一个页面,提交表单时将调用javascript函数作为

<form name="users" method="post" onSubmit="returncheckCorrect()" action="Registeration.jsp">

然后你的javascript会检查你的答案,比如:

<script type="text/javascript">
function returncheckCorrect() {
    var x = document.getElementsByName("userName")
    if (your condition) {
        alert("Redirecting");
        return true;
    } else {
        alert("Not Redirecting");
        return false;
    }
}
// return false; // lol, see why indentation is useful ?
</script>

然后(如果(您的条件==true))您的java脚本将重定向到第二个页面,您希望在类似的scriptlet中获得值

<% uname=""+request.getAttribute("username"); %>

请确保您的代码是以这种方式编写的。

下面是我试过的代码,正如你所说,它的工作

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
    function chkme() {
        var x = document.getElementById('textfield');
        if (x.value == 'sarin') {
            alert("success");
        } else {
            alert("failed");
        }
        return true;
    }
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form id="form1" name="form1" method="post" onsubmit="chkme();"
        action="">
        <input type="text" name="textfield" id="textfield" /> <input
            type="text" name="textfield2" id="textfield2" /> <input
            type="submit" name="button" id="button" value="Submit" />
    </form>
    <%
        if (request.getMethod().equals("POST")) {
            String textfield = request.getParameter("textfield");
            String textfield2 = request.getParameter("textfield2");
    %>
    <%=textfield%>
    <br />
    <%=textfield2%>
    <%
        }
    %>
</body>
</html>