微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过ajax和form提交 转向

这次本想尝试用ajax来提交表单来登录,但是遇到了很多问题,下面就是相关的总结。
ajax提交:
第一步:ajax提交给servlet数据,进过相关的处理后
第二步:servlet后可以通过下面的方法返回msg数据给前台
Stringmsg= "error" ; response.getWriter().write(msg);
返回信息!(如果是要转跳进行第三部,否则对返回的信息做相应的处理,如本例子的弹出提示框。)
第三部:通过前台中的js来实现页面跳转(如果是放在web-inf中jsp,jsp要在web.xml中部署后,这样的url才会有效,参考:http://blog.csdn.net/wanghaiping1993/article/details/23510411中关于web-inf中jsp如何访问
window.location.href= "${pageContext.request.contextpath}/main.jsp" ;

form提交:
第一步:写好form表单后,向servlet提交信息
第二部:通过下面的语句进行重定向来实现页面跳转(这样使用,在web-inf中jsp就不用在web-inf中进行部署了)
request.getRequestdispatcher("/WEB-INF/jsp/***.jsp").forward(request,response);


登录界面:
<%@ page language = "java" import = "java.util.*" pageEncoding = "utf-8" %>
<%
String path = request.getcontextpath();
String basePath = request.getScheme()+ "://" +request.getServerName()+ ":" +request.getServerPort()+path+ "/" ;
%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html >
< head >
< base href = " <%= basePath %> " >
< title > My JSP 'login.jsp' starting page </ title >
< script type = "text/javascript" src = "js/jquery-1.8.0.min.js" ></ script >
< script type = "text/javascript" >
function ajax_submit(){
var username=document.getElementsByName( "username" )[0].value;
password=document.getElementsByName( "password" /* //一定要加入jquery.js */
$.ajax({
url: '${pageContext.request.contextpath }/Userservlet?method=login' ,
type: 'post' data: 'username=' +username+ '&password=' +password,239)">success: (msg) {
if ((msg== "error" )) {
alert( "用户名或者密码错误!!" );
} else if "success" ))
window.location.href= "${pageContext.request.contextpath}/main.jsp" ;
}
});
}
</ script >

</ head >
< body >
< div align = "center" style =" margin : auto ;" >
<%-- <form action="" method="post">
--%>
< table >
< tr > 用户名 < input type = "text" name = "username" ></ tr >< br >
< tr > 密码: < input type = "password" name = "password" ></ tr >< br >
< tr > < input type = "submit" onclick = "ajax_submit()" value = "提交" ></ tr >
</ table >
</ div >
<%-- </form>
--%>
</ body >
</ html >

原文地址:https://www.jb51.cc/ajax/165026.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐