jQuery+Ajax实现用户登录

这里仅仅将上篇原生js实现时的.js文件用jQuery实现一遍:(功能完全一致)

 

$(function () {
	$("#login").submit(function(event) {
		event.preventDefault();
		if ($("#user").val().length == 0) {
			$("#inform").text("用户名不能为空");
		}else if ($("#password").val().length == 0) {
			$("#inform").text("密码不能为空");
		}else if ($("#user").val().length != 0 && $("#password").val().length != 0) {
			if(!(/(^[1-9]\d*$)/.test($("#user").val()))){
				$("#inform").text("用户名含有非法字符");//有其他字母或者符号型字符的存在
			}else if((/(^[1-9]\d*$)/.test($("#user").val()))){
				$.ajax({
					url:"loginJson.jsp",
					data:{User:$("#user").val(),Password:$("#password").val()},
					success:function(result){
						//alert(result);
						var logindata = JSON.parse(result);
						if(logindata.checkResult == null){
							$("#inform").text("该用户不存在");
						}else if (logindata.checkResult == true) {
							window.location.href="index.jsp";
							//alert("done");
						}else if (logindata.checkResult == false){
							$("#inform").text("密码错误");
						}
					}
				});
			}
		}
	});
});

注意一点:event.preventDefault()方法可避免form的action跳转。
 

 

你可能感兴趣的:(J2EE)