版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
ajax可以在页面不刷新的情况下完成与服务器的交互!
代码演示:
1.juqery代码:
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src= "js/jquery1.js"></script>
</head>
<body>
姓名:<input type="text" name = "name" id="name" /><br />
密码:<input type="text" name = "pwd" id="pwd"/><br />
<input type="button" value="登录" />
<div id = "show"></div>
<script>
$(function(){
$(function(){
$(":button").on("click",function(){
$.ajax({
url:"logIn",
type:"post",
data:{
name:$("#name").val(),
pwd:$("#pwd").val()
},
dataType:"text",
success:function(data){
if(data == "ok"){
window.location.href = "test.jsp";
}else{
$("#show").text("登录失败!");
}
}
})
})
});
});
</script>
</body>
</html>
2.servlet代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = "admin";
String pwd = "123456";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String ajaxName = request.getParameter("name");
String ajaxPwd = request.getParameter("pwd");
if(name.equals(ajaxName)&&pwd.equals(ajaxPwd)){
out.print("ok");
}else{
out.print("error");
}
out.flush();
out.close();
}