Day73 jQuery事件、遍历、异步请求
1.思维导图
2.代码部分
-
-
获取第2个li节点的文本内容
-
<head> <title>jquery案例</title> <script src="${pageContext.request.contextPath}/js/jquery-3.2.1.min.js"></script> <script> /** * 获取第2个li节点的title属性 */ function fn1() { //基本过滤选择器 : 从位置的角度 var title = $("li:eq(1)").attr("title"); console.log(title); } function fn2() { //子元素过滤选择器:从子元素的角度 var title = $("ul :nth-child(2)").attr("title"); console.log(title); } /** * 获取第2个li节点的文本内容 */ function fn3() { //val():获取value属性 var title = $("li:eq(1)"); var content = title.html(); console.log(content); } </script> </head> <body> <ul> <li title='pineapple'>菠萝</li> <li title='banana'>香蕉</li> <li title='peach'>桃子</li> </ul> <button onclick="fn1()">获取1</button> <button onclick="fn2()">获取2</button> <button onclick="fn3()">获取3</button> </body>
<head> <title>事件</title> <script src="js/jquery-3.2.1.min.js"></script> <script> //js方式一 function fn1() { console.log("点击方式1") } window.onload = function () { //js方式二:js的dom分配 var ele = document.getElementById("btn1"); ele.onclick = function () { console.log("点击方式2") } //jquery方式 $("#btn2").click(function () { console.log("点击方式3") }); } </script> </head> <body> <button onclick="fn1()">点击1</button> <button id="btn1">点击2</button> <button id="btn2">点击3</button> </body>
<head> <title>事件绑定</title> <script src="js/jquery-3.2.1.min.js"></script> <script> $(function () {//监听页面加载完成 //jquery事件绑定方式一 $("#btn").click(function () { console.log("点击方式1") }); //jquery事件绑定方式二 //第一个参数:绑定的事件名 //第二个参数:监听器 $("#btn2").bind("click",function () { console.log("点击方式2") }) }) </script> </head> <body> <button id="btn" >点击1</button> <button id="btn2" >点击2</button> </body>
-
- 输入框获取焦点时,输入框内容置为空
-
- 失去焦点时,输入内容设置为 "请输入用户名"
<head> <title>事件案例</title> <script src="js/jquery-3.2.1.min.js"></script> <script> $(function () { $("#username").focus(function () {//监听获取焦点 console.log("获取焦点"); //只有当value=”请输入用户名“ if ($("#username").val() == "请输入用户名") { $("#username").val(""); } }); $("#username").blur(function () {//监听失去焦点 console.log("失去焦点") if ($("#username").val() == "") { $("#username").val("请输入用户名"); } }); }) </script> </head> <body> <input type="text" id="username" value="请输入用户名"/> </body>
//jquery方式一
function fn2() {
var lis = $("ul > li");
lis.each(function (index,element) {
//index:当前元素的脚标
//element:当前元素(js对象)
console.log("index : " + index);
console.log("text : " + element.innerHTML);
console.log("text : " + $(element).html());
});
}
//jquery方式一
function fn3() {
var lis = $("ul > li");
lis.each(function (index) {
console.log("index : " + index);
//this:内置对象,js对象,当前元素
console.log(this.innerHTML);
console.log($(this).html());
})
}
- 方式二
//jquery方式二
function fn4() {
var lis = $("ul > li");
$.each(lis,function (index,element) {
console.log(index);
console.log(element.innerHTML);
console.log(this.innerHTML);
})
}
//Servlet.java
@WebServlet(name = "Demo01Servlet" ,urlPatterns = "/demo01") public class Demo01Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); String msg = "登录成功"; boolean flag = true; if (username.equals("root") && password.equals("root")) { msg = "登录成功"; flag = true; } else { msg = "登录失败"; flag = false; } Map<String,Object> map = new HashMap<>(); map.put("msg",msg); map.put("flag",flag); ObjectMapper objectMapper = new ObjectMapper(); String jsonStr = objectMapper.writeValueAsString(map); //服务器告诉浏览器,响应正文是json字符串,浏览器应该以utf-8对响应正文进行解码 response.setContentType("application/json;charset=utf-8");
response.getWriter().write(jsonStr); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response);
}
}
//$.get(url,data,callback,type)
<head> <title>jQuery异步请求之get</title> <script src="js/jquery-3.2.1.min.js"></script> <script> function fn1() { //$.get(url,data,callback,type); var url = "${pageContext.request.contextPath}/demo01"; var data = {"username": "root", "password": "root1234"}; var callback = function (data) {//data:服务器的响应正文 //type=json,get方法内部就会自动将服务器返回的json字符串解析成js对象 console.log(data.flag); console.log(data.msg); }; var type = "json"; $.get(url, data, callback, type); } function fn2() { $.get("${pageContext.request.contextPath}/demo01", { "username": "root", "password": "root" }, function (data) { console.log(data.flag); console.log(data.msg); }, "json"); } </script> </head> <body> <button onclick="fn1()">get请求1</button> <button onclick="fn2()">get请求2</button> </body>
//Servlet.java
@WebServlet(name = "Demo02Servlet" ,urlPatterns = "/demo02") public class Demo02Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); String msg = "登录成功"; boolean flag = true; if (username.equals("root") && password.equals("root123")) { msg = "登录成功"; flag = true; } else { msg = "登录失败"; flag = false; } Map<String,Object> map = new HashMap<>(); map.put("msg",msg); map.put("flag",flag); JsonUtils.writeJsonStr(response,map); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
//$.post(url,data,callback,type)
<head> <title>jQuery异步请求之post</title> <script src="js/jquery-3.2.1.min.js"></script> <script> function fn1() { //$.post(url,data,callback,type); $.post("${pageContext.request.contextPath}/demo02",{ "username":"root", "password":"root123" },function (data) { console.log(data); },"json"); } </script> </head> <body> <button onclick="fn1()">post请求</button> </body>
//JsonUtils.java
public class JsonUtils { /** * 将java对象转换成json字符串 * @param object * @return * @throws Exception */ public static String toJsonStr(Object object) throws Exception { return new ObjectMapper().writeValueAsString(object); } /** * 将java对象转换为json字符串,并将json字符串响应到浏览器 * @param response : 响应对象 * @param object : java对象 */ public static void writeJsonStr(HttpServletResponse response , Object object){ response.setContentType("application/json;charset=utf-8");
try { String jsonStr = toJsonStr(object); response.getWriter().write(jsonStr);
}catch (Exception e) { e.printStackTrace();
}
}
}
<head> <title>jQuery异步请求之ajax</title> <script src="js/jquery-3.2.1.min.js"></script> <script> function fn1() { $.ajax({ type:"post", url:"${pageContext.request.contextPath}/demo02", data:{ "username" :"root", "password" :"root123" }, success:function (data) { console.log(data.flag); console.log(data.msg); }, dataType:"json", }); } </script> </head> <body> <button onclick="fn1()">ajax请求</button> </body> </html>
//UserDao.java
public class UserDaoImpl implements UserDao { @Override public User checkUsername(String username) throws Exception { return new QueryRunner(JDBCUtils.getDataSource()) .query("select * from tb_user where username = ?", new BeanHandler<User>(User.class), username); } }
//UserService.java
public class UserServiceImpl implements UserService { private UserDao userDao = new UserDaoImpl(); @Override public boolean checkUsername(String username) throws Exception { User existUser = userDao.checkUsername(username); if (null != existUser) { //用户名已存在 return false; } else { //用户名可用 return true; } } }
//CheckUsernameServlet.java
request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); UserService userService = new UserServiceImpl(); try { boolean flag = userService.checkUsername(username); String msg = flag ? "用户名可用" : "用户名存在"; Map<String,Object> map = new HashMap<>(); map.put("flag",flag); map.put("msg",msg); //将map转换成json字符串,并将对应json字符串响应到浏览器 JsonUtils.writeJsonStr(response,map); } catch (Exception e) { e.printStackTrace(); }
//regist.jsp
<head> <title>用户注册</title> <script src="${pageContext.request.contextPath}/js/jquery-3.2.1.min.js"></script> <script> function checkUsername() { var username = $("#username").val(); console.log(username); $.post("${pageContext.request.contextPath}/checkUsername",{ "username":username, },function (data) { console.log(data); var flag = data.flag; var msg = data.msg; var btn = $("button[type='submit']"); if (flag) { //用户名可用 $("#span").html("<font color='#1e90ff'>"+msg+"</font>"); //让按钮可以点击 btn.attr("disabled",false); } else { //用户名存在 $("#span").html("<font color='green'>"+msg+"</font>"); //禁用按钮 btn.attr("disabled",true); } },"json"); } </script> </head> <body> <form action="${pageContext.request.contextPath}/regist" method="post"> 账户:<input type="text" name="username" id="username" onchange="checkUsername()"/><span id="span"></span><br> 密码:<input type="text" name="password"/><br> <button type="submit" >注册</button> </form> </body>