jquery+Ajax+servlet实现页面不刷新响应(1)

1、jsp页面代码

使用jquery封装好的方法调用ajax更加方便,所以别忘记导入jquery,其中,url设置为接收请求的后台页面, 传输的数据类型为json格式,json内容可以从表单中获取,提交方式为post,在回调函数中根据返回值写对应的代码即可,比如页面跳转、更改页面某一个元素等等。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Test</title>
<script src="js/jquery-3.3.1.js"></script>
<script src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){ 
	
    $.ajax({
        url : "${pageContext.request.contextPath}/DoLogin", //后台查询验证的方法
        dataTpye : "json",
        data : {
            "name" : $('#name').val(),
            "pwd" : $('#pwd').val()
        }, 
        type : "post",
        success : function(msg) {
            //根据后台返回前台的msg给提示信息加HTML
            if ("true" == msg) {
                
            	alert("success");
            } else {
                
                alert("failed");
            }
        },
        error:function(){  //请求失败的回调方法
        	alert("请求失败,请重试");
        }
    });
	});
});
</script>
</head>
<body>
	<form action="" method="POST">
		<input type="text" id="name">
		<input type="text" id="pwd">
		<input type="button" value="submit" id="btn">
	</form>
	<a href="${pageContext.request.contextPath}/DoLogin?name=admin&pwd=hello">测试链接</a>
</body>
</html>

2、servlet代码

使用response对象进行响应。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String path = request.getContextPath();
		response.setContentType("text/html;charset=utf-8");
		//response.setContentType("application/text; charset=utf-8");
		request.setCharacterEncoding("utf-8");
		System.out.println("in servlet");
		PrintWriter out = response.getWriter();
		String name = (String)request.getParameter("name");
		String password = (String)request.getParameter("pwd");
            if(name.equals(password)){
		        out.print("true");
            }
            else{
                out.println("false");
            }
		    System.out.print("cross");
		
	
	}

 

结果图

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值