Ajax 应用 with jquery

一、前端部分
  • 1.1 html 部分
  • 1.2 js 部分
  • 二、后端部分
  • 三、运行结果

最近在学习 jquery,学习到 ajax 部分了,就把之前做过内容使用 jquery 实现一遍

这两篇是我使用 纯 js 实现的,可以先看这个,注解我也写的比较详细

Ajax 技术学习 (Java EE 实现) —— 用户账户的验证

Ajax 技术学习(JavaEE)—— 实现二级下拉联动

一、前端部分

1.1 html 部分

<form action="">
用户名:<input type="text" name="username" id="username" /><span id="info"></span><br />
密 码:<input type="password" name="password" id="password" /></br>
<input type="submit" id="submit" value="提交" />
</form>

1.2 js 部分

这里是 jQuery 的语法,写起来相比原生的 js 代码简洁太多,发送 get 请求 或者 post 请求均使用大写即可

<script type="text/javascript">
$(function () {
$("#username").bind("blur", function() {
txt = $("#username").val();
$.ajax({
type: "POST",
url: "AjaxCheck",
data: {
username:txt
},
success: function(res) {
console.log("发送成功:"+res);
if (res == "true") {
$("#info").html("<font color='green'>该账号可以使用</font>");
} else{
$("#info").html("<font color='red'>该账号不可以使用</font>");
}
},
error: function() {
console.log("糟糕,出现错误了");
}
});
});
});
</script>

二、后端部分

后端我依然是采用的 Java EE 来实现的,和前面写过的验证基本相差不大,后端的路径是 AjaxCheck

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");

// 获取前端传送过来的数据
String username = request.getParameter("username");

// 打印得到数据
System.out.println(username);

//
PrintWriter out = response.getWriter();
if (username.equals("admin")) {
out.write("false");
} else {
out.write("true");
}
out.flush();
out.close();
}

三、运行结果

Ajax 技术应用 (jQuery 实现账户验证)_html

Ajax 技术应用 (jQuery 实现账户验证)_jquery_02