【JQ,JS】表单接口数据交互写法 [课堂笔记]

课堂笔记 胡成

胡小哥课堂笔记《第二章》
关于js,jq登入时接口数据验证的写法,本人课堂练习时写了JS与JQ俩种接口数据验证写法。现在下面放代码!

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>表单验证接口数据交互写法</title>
	</head>

	<body>
		<form action="#" method="post">
			<p>用户名:<input id="uname" type="text"></p>
			<p>密 码:<input id="pwd" type="text"></p>
			<input type="submit" value="登入" onclick="return check()" />
		</form>
		<script src="js/jquery-1.8.3.min.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			function checkUser() { //非空验证用户名
				var uname = document.getElementById("uname");
				if(uname.value.trim() == "") {
					alert("用户名不能为空!");
					return false;
				}
				return true;
			}

			function checkPwd() { //非空验证密码
				var pwd = document.getElementById("pwd");
				if(pwd.value.trim() == "") {
					alert("密码不能为空!");
					return false;
				}
				return true;
			}

			//验证用户,密码是否正确
			function login() {
				var uname = document.getElementById("uname").value; //获取用户名输入框对象
				var pwd = document.getElementById("pwd").value; //获取用密码输入框对象

				//				js登入接口数据交互写法
//				var obj = $.ajax({
//					url: "http://localhost:62716/ttt/hc/UserLogin",
//					async: true, //默认为true表示异步请求,false表示同步请求
//					type: "post",
//					data: {
//						"user": uname,
//						"upwd": pwd
//					},
//					success: function(msg) {
//						if(msg) {
//							location.href = "ss1.html";
//							sessionStorage.name = uname; //用本地存储保存用户名
//							return true;
//						} else {
//							alert("用户名获取密码错误!");
//							return false;
//						}
//					},
//					error: function(a, e) {
//						alert("系统错误!请联系管理员!" + a + "\n" + e);
//					}
//				});
//				return false;

				//				js登入接口数据交互写法
				var ajax;
				if(window.XMLHttpRequest) {
					ajax = new XMLHttpRequest(); //判断IE浏览器是否兼容
				} else { //ie5,6
					ajax = new ActiveXObject("Microsoft.HTTP")
				}
				ajax.open("post", "http://localhost:62716/ttt/hc/UserLogin", true); //接口链接路径 异步请求
				ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //不写报错
				ajax.send("user=" + uname + "&upwd=" + pwd); //发送数据
				ajax.onreadystatechange = function() {//当请求被发送到服务器时执行事件
					if(ajax.status == 200 && ajax.readyState == 4) { //判断发送数据状态
						var str = ajax.responseText; //返回数据(用户名与密码)
						if(str == "true") { //判断数据
							location.href = "ss1.html"; //页面跳转
							sessionStorage.name = uname; //用本地存储保存用户名
							return true;
						}
						alert("用户名获取密码错误!")
					}
				}
				return false;
			};

			function check() {//判断3种函数是否为true,返回为true,表单验证通过。
				if(checkUser() && checkPwd() && login()) {
					return true;
				}
				return false;
			}
		</script>
	</body>

</html>

——来自胡小哥课堂笔记

还能输出{{restrictNumber}}个字符  
  • {{reply.author}}

    {{CommonUtil.formateDate(reply.ac_CommentDate).shortTime}}
  • 回复了{{Comments.author}} :