1.什么是jQuery
它是一个轻量级的javascript类库
注意:就一个类"jQuery",简写“$” 2.jQuery优点
2.1总是面向集合
2.2多行操作集于一行
3. hello jQuery
3.1 导入js库()
3.2 $(fn)做为程序入口
代码演示
首先创建一个项目,创建Folder文件命名为js,放入jquery.min,如图
demo1:导入js
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- src:全路径名的好处,更改时不会出错-->
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
/* jquery入门程序 */
/*$(fn)、$(document).read(fn)与window.onload的区别 */
$(function(){
alert("hello jquery");
})
$(document).ready(function(){
alert("hello jquery2");
})
window.onload = function(){
alert("hello jquery3");
}
</script>
</head>
<body>
</body>
</html>
( f n ) 、 (fn)、 (fn)、(document).ready(fn)与window.onload的区别?
主要项目维护的时候用
<script type="text/javascript">
/* jquery入门程序 */
/*$(fn)、$(document).read(fn)与window.onload的区别 */
window.onload = function(){
alert("hello jquery3");
}
$(function(){
alert("hello jquery1");
})
$(document).ready(function(){
alert("hello jquery2");
})
</script>
问:先后顺序
答:jquery1,jquery2,jquery3
<script type="text/javascript">
/* jquery入门程序 */
/*$(fn)、$(document).read(fn)与window.onload的区别 */
window.onload = function(){
alert("hello jquery3");
}
$(document).ready(function(){
alert("hello jquery2");
})
$(function(){
alert("hello jquery");
})
</script>
问:顺序
答:jquery2,jquery1,jquery3
小结: ( f n ) 、 (fn)、 (fn)、(document).read(fn)是等价的,哪个代码再前面哪个先执行
jsp的dom数结构加载完毕即刻调用方法
window.onload最后执行
jsp的dom树加载完、css、js等静态资源加载完毕执行
4.jQuery三种工厂方法
为了获取jQuery一个类的实例
4.1 jQuery(exp[,context])
(有很多种api查看,只大概讲述以下五种)
exp:选择器
context:上下文,环境/容器,documemt
注意:选择器,css选择器
标签选择器
ID选择器
类选择器
包含选择器:E1 E2
组合选择器:E1,E2,E3
自定义选择器::exp
代码演示
创建一个Jquery类:
package com.myy;
public class Jquery {
public final static int xxx = 33;
public int aaa = 33;
public static void bbb() {
}
public void ccc() {
}
public static void main(String[] args) {
}
}
demo2:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
$(function(){
//利用a标签jquery实例
$("a").click(function(){
alert("点开了");
});
})
</script>
</head>
<body>
<p>
<a id="a1" class="c1" href="#">点我1</a>
</p>
<p>
<a id="a2" class="c2" href="#">点我2</a>
</p>
<p>
<a id="a3" class="c3" href="#">点我3</a>
</p>
<div>
<a id="a4" class="c1" href="#">点我4</a>
</div>
<div>
<p>
<a id="a5" class="c1" href="#">点我5</a>
</p>
</div>
<span>点我</span>
</body>
</html>
运行结果:
jquery好处:代码缩减了
<script type="text/javascript">
$(function(){
//利用a标签jquery实例
/* $("a").click(function(){
alert("点开了");
}); */
//利用id=a3获取jquery实例
/* $("#a3").click(function(){
alert("点开了");
}); */
//class=c1类选择器
/* $(".c1").click(function(){
alert("点开了");
}); */
//包含选择器(p里面包含a)
/* $("p a").click(function(){
alert("点开了");
}); */
//组合选择器 (可以不同加入多个事件)
/* $("a,span").click(function(){
alert("点开了");
}); */
})
</script>
当我想再div容器里面的a标签加入事件
//讲解第二个参数的作用(在div标签内部寻找a标签,然后给找到的标签添加事件)
//如果第二个参数没有填写,那么默认是document
$("a","div").click(function(){
alert("点开了");
});
4.2 jQuery(html)
html:基于html的一个字符串
代码演示
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
$(function(){
//自定义选择器
$(":input[name='name1']").click(function(){
//在id=selId1的select的jquery实例上追加"<option value='1'>湖南省</option>"的html jquery实例
$("#selId1").append("<option value='1'>湖南省</option>");
});
$(":input[name='name1']").click(function(){
//将"<option value='1'>长沙</option>"的html jquery实例追加到id=selId2的select标签jquery实例中
$("<option value='1'>长沙</option>").appendTo("#selId2");
});
})
</script>
</head>
<body>
<select id="selId1">
<option value="-1">---请选择---</option>
</select>
<select id="selId2">
<option value="-1">---请选择---</option>
</select>
<input name="name1" value="add1" type="button">
<input name="name2" value="add2" type="button">
<input type="hidden" id="h1" value="h1">
<input type="hidden" id="h2" value="h2">
<input type="hidden" id="h3" value="h3">
</body>
</html>
运行结果:
刚开始运行显示:
当点击add1加入时:
点击几次加几次:
public Jquery(int html) {
super();
this.aaa = html;
}
4.3 jQuery(element)
element:js对象,表示一个html元素对象
js对象与jquery对象的相互转换
注意:$就是jQuery简写
代码演示
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
$(function(){
//自定义选择器
$(":input[name='name1']").click(function(){
//在id=selId1的select的jquery实例上追加"<option value='1'>湖南省</option>"的html jquery实例
$("#selId1").append("<option value='1'>湖南省</option>");
});
$(":input[name='name1']").click(function(){
//将"<option value='1'>长沙</option>"的html jquery实例追加到id=selId2的select标签jquery实例中
$("<option value='1'>长沙</option>").appendTo("#selId2");
//jquery获取
var $h1 = $("#h1");
alert($h1.val());
//jquery对象转js对象
//第一种:看做集合
//var h1Node = $h1.get(0);
//第二种:看做数组
/* var h1Node = $h1[0];
alert(h1Node.value); */
var h2Node = document.getElementById("h2");
alert(h2Node.value);
//js对象转jquery对象
$h2Node = $(h2Node);
alert($h2Node.val());
});
})
</script>
</head>
<body>
<select id="selId1">
<option value="-1">---请选择---</option>
</select>
<select id="selId2">
<option value="-1">---请选择---</option>
</select>
<input name="name1" value="add1" type="button">
<input name="name2" value="add2" type="button">
<input type="hidden" id="h1" value="h1">
<input type="hidden" id="h2" value="h2">
<input type="hidden" id="h3" value="h3">
</body>
</html>
点击add1测试会依次弹 h1,h2,h2
5. jQuery程序的入口
$(document).ready(fn)
$(fn);
6. this指针的作用
6.1 事件源(获取当前按钮的按钮值)
6.2 当前元素(点击按钮,获取所有a标签的值)
6.3 插件一章再讲
代码演示
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
$(function(){
$(":input").click(function(){
//this指的是你当前点击的事件源
alert(this.value);
$("a").each(function(index,item){//item和this一个意思
//this指的是当前元素
alert(index+","+$(this).html()+","+$(item).html());
});
});
})
</script>
</head>
<body>
<p>
<a id="a1" class="c1" href="#">点我1</a>
</p>
<p>
<a id="a2" class="c2" href="#">点我2</a>
</p>
<p>
<a id="a3" class="c3" href="#">点我3</a>
</p>
<div>
<a id="a4" class="c1" href="#">点我4</a>
</div>
<div>
<p>
<a id="a5" class="c1" href="#">点我5</a>
</p>
</div>
<input type="button" value="ok">
</body>
</html>
测试运行结果
依次弹出:
ok
0,点我1,点我1
1,点我2,点我2
2,点我3,点我3
3,点我4,点我4
4,点我5,点我5
7.使用jquery动态给table添加样式
用jquery写表格隔行变色
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<style type="text/css">
.fen {
background: #ff66ff;
}
.yello {
background: #ffff66;
}
.red {
background: #ff3333;
}
</style>
<script type="text/javascript">
$(function(){
//获取第一行
$("table tr:eq(0)").addClass("yello");
//大于0
$("table tr:gt(0)").addClass("red");
//加事件
$("table tr:gt(0)").hover(function(){
$(this).removeClass.addClass("fen");
},function(){
$(this).removeClass.addClass("red");
});
})
</script>
<title>Insert title here</title>
</head>
<body>
<table border="1" width="100%">
<tr>
<td>书名</td>
<td>作者</td>
<td>点击量</td>
</tr>
<tr>
<td>圣墟</td>
<td>辰东</td>
<td>10万</td>
</tr>
<tr>
<td>飞剑问道</td>
<td>我吃西红柿</td>
<td>11万</td>
</tr>
<tr>
<td>杀神</td>
<td>逆苍天</td>
<td>22万</td>
</tr>
<tr>
<td>龙王传说</td>
<td>唐家三少</td>
<td>18万</td>
</tr>
<tr>
<td>斗破苍穹</td>
<td>天蚕拖豆</td>
<td>1万</td>
</tr>
</table>
</body>
</html>
运行结果:
鼠标移进变紫色,移出变红色:
二.jQuery插件
1. 插件机制简介
往jquery类库里面去扩展方法,这类方法就是jquery插件
2.json的三种格式
2.1 对象
{sid:'s01',sname:'zs'}
2.2 列表/数组
[1,3,4,5]
2.3 混合模式
{id:3,hobby:['a','b','c']}
代码演示
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
//json对象的字符串体现形式
var jsonObj1 = {
sid:'s001',
sname:'zhangsan'
};
//去后台F12获取显示
console.log(jsonObj1);
//json数组的字符串体现形式
var jsonArray1=[1,3,4,7];
console.log(jsonArray1);
//json混合模式的字符串体现模式
var jsons = {id:3,hobby:['a','b','c']};
console.log(jsons);
})
</script>
<title>Insert title here</title>
</head>
<body>
</body>
</html>
后台F12测试结果:
2. 插件基础:$ .extend和$.fn.extend
2.1 $.extend:对象的扩展(或继承)
$.extend(obj1,obj2,obj3[,…])
$.extend(obj1,obj2)
$ .extend(obj1)/$.method=function(options){…};
代码演示
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
//json对象的字符串体现形式
var jsonObj1 = {
sid:'s001',
sname:'zhangsan'
};
//去后台F12获取显示
console.log(jsonObj1);
//json数组的字符串体现形式
var jsonArray1=[1,3,4,7];
console.log(jsonArray1);
//json混合模式的字符串体现模式
var jsons = {id:3,hobby:['a','b','c']};
console.log(jsons);
var jsonObj3 = {
sid:'s002',
sname:'lisi',
hobby:['a','b','c']
};
//$.extend是用来扩展jQuery类属性或者方法所用
var jsonObj2 = {};
//用后面的对象扩充第一个对象
// $.extend(jsonObj2,jsonObj1);
//讲解值覆盖的问题,之前已经扩充的属性值会被后面的对象所覆盖,如果后面对象有新的属性,会继续扩充
//还能多个扩充1和3扩充2
$.extend(jsonObj2,jsonObj1,jsonObj3);
console.log(jsonObj1);
})
</script>
<title>Insert title here</title>
</head>
<body>
</body>
</html>
运行结果
2.2 $.fn.extend
$.fn.extend(obj1)//$.fn.method=function(options){...};
代码演示
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
//json对象的字符串体现形式
var jsonObj1 = {
sid:'s001',
sname:'zhangsan'
};
//去后台F12获取显示
console.log(jsonObj1);
//json数组的字符串体现形式
var jsonArray1=[1,3,4,7];
console.log(jsonArray1);
//json混合模式的字符串体现模式
var jsons = {id:3,hobby:['a','b','c']};
console.log(jsons);
var jsonObj3 = {
sid:'s002',
sname:'lisi',
hobby:['a','b','c']
};
//$.extend是用来扩展jQuery类属性或者方法所用
var jsonObj2 = {};
//用后面的对象扩充第一个对象
// $.extend(jsonObj2,jsonObj1);
//讲解值覆盖的问题,之前已经扩充的属性值会被后面的对象所覆盖,如果后面对象有新的属性,会继续扩充
//还能多个扩充1和3扩充2
$.extend(jsonObj2,jsonObj1,jsonObj3);
console.log(jsonObj1);
$.extend({
hello:function(){
alert('来了');
}
});
$.hello();
// $.fn.extend是用来扩充jquery实例的属性或者方法所用
$.fn.extend({
sayHello:function(){
alert('想你');
}
});
$("#pink").sayHello();
alert("pink");
})
</script>
<title>Insert title here</title>
</head>
<body>
<span id="pink">pink</span>
</body>
</html>
测试:分别弹出来了,想你,pink,页面显示pink
最常用的类方法拓展的比较少,一般类属性拓展比较多,实例方法
关于类的用的属性,关于实例用的是方法
3. jQuery插件的添加
其实就是给jQuery添加新的实例方法或类方法,然后将功能封闭在其中
4. jQuery插件开发实例
4.1 命名
jquery.xxx.js
4.2 扩展实例方法
4.3 如何面向集合
4.4 如何多行集于一行
4.5 命名参数的写法
$.extend(defaults,options);
代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<title>Insert title here</title>
<style type="text/css">
.over{
background: #ff66ff;
}
.out{
background: #ffff66;
}
.head{
background: #ff3333;
}
</style>
<script type="text/javascript">
$(function(){
$("table").each(function(){
//给默认值
$("tr:eq(0)",this).addClass('head');
$("tr:gt(0)",this).addClass('out');
//添加动态效果
$("tr:gt(0)",this).hover(function(){
$(this).removeClass().addClass('over');
},function(){
$(this).removeClass().addClass('out');
});
});
})
</script>
</head>
<body>
<table id="t1" border="1" width="100%">
<tr>
<td>书名</td>
<td>作者</td>
<td>点击量</td>
</tr>
<tr>
<td>圣墟</td>
<td>辰东</td>
<td>10万</td>
</tr>
<tr>
<td>飞剑问道</td>
<td>我吃西红柿</td>
<td>11万</td>
</tr>
<tr>
<td>杀神</td>
<td>逆苍天</td>
<td>22万</td>
</tr>
<tr>
<td>龙王传说</td>
<td>唐家三少</td>
<td>18万</td>
</tr>
<tr>
<td>斗破苍穹</td>
<td>天蚕拖豆</td>
<td>1万</td>
</tr>
</table>
<table id="t2" border="1" width="100%">
<tr>
<td>书名</td>
<td>作者</td>
<td>点击量</td>
</tr>
<tr>
<td>圣墟</td>
<td>辰东</td>
<td>10万</td>
</tr>
<tr>
<td>飞剑问道</td>
<td>我吃西红柿</td>
<td>11万</td>
</tr>
<tr>
<td>杀神</td>
<td>逆苍天</td>
<td>22万</td>
</tr>
<tr>
<td>龙王传说</td>
<td>唐家三少</td>
<td>18万</td>
</tr>
<tr>
<td>斗破苍穹</td>
<td>天蚕拖豆</td>
<td>1万</td>
</tr>
</table>
</body>
</html>
鼠标移进是紫色显示如下图:
问:当客户要求变颜色:
如何简化代码
定义插件
创建文件:
jquery.table.css样式
@charset "UTF-8";
.fen {
background: #ff66ff;
}
.yellow {
background: #ffff66;
}
.red {
background: #ff3333;
}
.blue {
background: #9999ff;
}
.green {
background: #bbff99;
}
.hui {
background: #d6d6c2;
}
jquery.table.js写插件
$(function(){
//定义一个默认样式
var defaults = {
head : 'fen',
out : 'yellow',
over : 'red'
}
$.fn.extend({
//使用return的原因是让该实例方法支持链编程,好比StringBuffter
bgColor:function(defaults,option){
//这里this指的是插件本身,可以看成一个jquery实例
return this.each(function(){
//这里this指的是当前元素
$("tr:eq(0)",this).addClass(defaults.head);
$("tr:gt(0)",this).addClass(defaults.out);
//添加动态效果
$("tr:gt(0)",this).hover(function(){
$(this).removeClass().addClass(defaults.over);
},function(){
$(this).removeClass().addClass(defaults.out);
});
});
}
});
})
demo
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="${pageContext.request.contextPath }/jquery/table/css/jquery.table.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/jquery/table/js/jquery.table.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
$(function(){
$("table").bgColor({
head : 'blue',
out : 'green',
over : 'hui'
});
})
</script>
</head>
<body>
<table id="t1" border="1" width="100%">
<tr>
<td>书名</td>
<td>作者</td>
<td>点击量</td>
</tr>
<tr>
<td>圣墟</td>
<td>辰东</td>
<td>10万</td>
</tr>
<tr>
<td>飞剑问道</td>
<td>我吃西红柿</td>
<td>11万</td>
</tr>
<tr>
<td>杀神</td>
<td>逆苍天</td>
<td>22万</td>
</tr>
<tr>
<td>龙王传说</td>
<td>唐家三少</td>
<td>18万</td>
</tr>
<tr>
<td>斗破苍穹</td>
<td>天蚕拖豆</td>
<td>1万</td>
</tr>
</table>
<table id="t2" border="1" width="100%">
<tr>
<td>书名</td>
<td>作者</td>
<td>点击量</td>
</tr>
<tr>
<td>圣墟</td>
<td>辰东</td>
<td>10万</td>
</tr>
<tr>
<td>飞剑问道</td>
<td>我吃西红柿</td>
<td>11万</td>
</tr>
<tr>
<td>杀神</td>
<td>逆苍天</td>
<td>22万</td>
</tr>
<tr>
<td>龙王传说</td>
<td>唐家三少</td>
<td>18万</td>
</tr>
<tr>
<td>斗破苍穹</td>
<td>天蚕拖豆</td>
<td>1万</td>
</tr>
</table>
</body>
</html>
答:当客户需要更改颜色时,只需要该如下:
架构优化
创建文件:
抽取头部文件:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE>
<link href="${pageContext.request.contextPath }/jquery/table/css/jquery.table.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/jquery/table/js/jquery.table.js"></script>
demo
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/jsp/common/head.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
$(function(){
$("table").bgColor({
head : 'blue',
out : 'green',
over : 'hui'
});
})
</script>
</head>
<body>
<table id="t1" border="1" width="100%">
<tr>
<td>书名</td>
<td>作者</td>
<td>点击量</td>
</tr>
<tr>
<td>圣墟</td>
<td>辰东</td>
<td>10万</td>
</tr>
<tr>
<td>飞剑问道</td>
<td>我吃西红柿</td>
<td>11万</td>
</tr>
<tr>
<td>杀神</td>
<td>逆苍天</td>
<td>22万</td>
</tr>
<tr>
<td>龙王传说</td>
<td>唐家三少</td>
<td>18万</td>
</tr>
<tr>
<td>斗破苍穹</td>
<td>天蚕拖豆</td>
<td>1万</td>
</tr>
</table>
<table id="t2" border="1" width="100%">
<tr>
<td>书名</td>
<td>作者</td>
<td>点击量</td>
</tr>
<tr>
<td>圣墟</td>
<td>辰东</td>
<td>10万</td>
</tr>
<tr>
<td>飞剑问道</td>
<td>我吃西红柿</td>
<td>11万</td>
</tr>
<tr>
<td>杀神</td>
<td>逆苍天</td>
<td>22万</td>
</tr>
<tr>
<td>龙王传说</td>
<td>唐家三少</td>
<td>18万</td>
</tr>
<tr>
<td>斗破苍穹</td>
<td>天蚕拖豆</td>
<td>1万</td>
</tr>
</table>
</body>
</html>
三.ajax
1. jackson
Jackson是一个简单基于Java应用库,Jackson可以轻松的将Java对象转换成json对象
和xml文档,同样也可以将json、xml转换成Java对象
核心代码:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(obj);
int count = md.getColumnCount();
map.put(md.getColumnName(i), rs.getObject(i));
代码演示
创建Student实体类:
package com.myy.entity;
public class Student {
private String sid;
private String sname;
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Student(String sid, String sname) {
super();
this.sid = sid;
this.sname = sname;
}
public Student() {
super();
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + "]";
}
}
导入jar包
分享:
链接:https://pan.baidu.com/s/1Hqj5pttTt3XHkEXwmGFiZQ
提取码:g9jz
Demo1
package com.myy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myy.entity.Student;
/**
* 后台json的三种格式的体现形式
* @author myy
*
*/
public class Demo1 {
public static void main(String[] args) throws JsonProcessingException {
//json对象
Student stu1 = new Student("s001","小明");
ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(stu1));
//json数组
Student stu2 = new Student("s002","小白");
List<Student> list1 = new ArrayList<>();
list1.add(stu1);
list1.add(stu2);
System.out.println(om.writeValueAsString(list1));
//json混合格式
Map<String, Object> map = new HashMap<String, Object>();
map.put("total", 2);
map.put("stus", list1);
System.out.println(om.writeValueAsString(map));
}
}
运行结果:
json基础,后台版的json格式,用jquery把这种形式传入到前台显示
2. jackson将java–>json
2.1 JavaBean/Map
{}
2.2 数组/List/Set
[]
2.3 类里嵌类
混合模式
代码演示对比
package com.myy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* javaBean(实体类)与Map集合转换成json字符串格式是一样的
* @author myy
*
*/
public class Demo2 {
public static void main(String[] args) throws JsonProcessingException {
Map<String, Object> stu1 = new HashMap<String, Object>();
stu1.put("sid", "s001");
stu1.put("sname", "小明");
ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(stu1));
//{"sid":"s001","sname":"小明"}
Map<String, Object> stu2 = new HashMap<String, Object>();
stu2.put("sid", "s002");
stu2.put("sname", "小白");
List<Map<String, Object>> list1 = new ArrayList<Map<String,Object>>();
list1.add(stu1);
list1.add(stu2);
System.out.println(om.writeValueAsString(list1));
//[{"sid":"s001","sname":"小明"},{"sid":"s002","sname":"小白"}]
}
}
运行结果
结果和上面1的一样,map是无序
3. java->json死循环
忽略双向关联的一个方向即可
@JsonIgnore/程序控制
代码演示
学生和老师是多对多的关系,用如下类描写:
Student
package com.myy.entity;
import java.util.HashSet;
import java.util.Set;
public class Student {
private String sid;
private String sname;
private Set<Teacher> teas = new HashSet<>();
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public Set<Teacher> getTeas() {
return teas;
}
public void setTeas(Set<Teacher> teas) {
this.teas = teas;
}
public void setSname(String sname) {
this.sname = sname;
}
public Student(String sid, String sname) {
super();
this.sid = sid;
this.sname = sname;
}
public Student(String sid, String sname, Set<Teacher> teas) {
super();
this.sid = sid;
this.sname = sname;
this.teas = teas;
}
public Student() {
super();
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + ", teas=" + teas + "]";
}
}
Teacher
package com.myy.entity;
import java.util.HashSet;
import java.util.Set;
import javax.print.attribute.HashAttributeSet;
public class Teacher {
private String tid;
private String sname;
private Set<Student> stus = new HashSet<>();
public String getTid() {
return tid;
}
public void setTid(String tid) {
this.tid = tid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Set<Student> getStus() {
return stus;
}
public void setStus(Set<Student> stus) {
this.stus = stus;
}
public Teacher(String tid, String sname, Set<Student> stus) {
super();
this.tid = tid;
this.sname = sname;
this.stus = stus;
}
public Teacher() {
super();
}
@Override
public String toString() {
return "Teacher [tid=" + tid + ", sname=" + sname + ", stus=" + stus + "]";
}
}
demo
package com.myy;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myy.entity.Student;
import com.myy.entity.Teacher;
/**
* @author myy
*
*/
public class Demo3 {
public static void main(String[] args) throws JsonProcessingException {
Student stu1 = new Student("s001","小猪");
Student stu2 = new Student("s002", "小熊");
Teacher tea1 = new Teacher("t001","李",null);
Teacher tea2 = new Teacher("t002","刘",null);
Set<Teacher> teas = new HashSet<>();
teas.add(tea1);
teas.add(tea2);
stu1.setTeas(teas);
Set<Student> stus = new HashSet<>();
stus.add(stu1);
stus.add(stu2);
tea1.setStus(stus);
ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(stu1));
}
}
运行结果:
当加上如下代码:
tea1.setStus(stus);
运行结果会报错:
彼此之间相互调用
解决:
json死循环问题
由双向绑定改成单向绑定,也就是说将彼此之间的关系交于一方维护 @JsonIgnore:将彼此循环调用的属性忽略,不参与对象转成json格式
去Teacher加上如下:
@JsonIgnore
再重新运行一次
运行结果:
4. $.ajax实现省市联动
利用map集合存储数据,然后利用把数据以json格式传入前台,然后jsp页面利用ajax接收,转译Json格式,然后给市和县添加change事件
JsonBaseDao
package com.myy.util;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonBaseDao extends BaseDao<Map<String,Object>> {
public List<Map<String,Object>> executeQuery(String sql, PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
return super.executeQuery(sql, pageBean, new Callback<Map<String,Object>>() {
@Override
public List<Map<String,Object>> foreach(ResultSet rs) throws SQLException, InstantiationException, IllegalAccessException {
/*
* 1、创建一个实体类的实例
* 2、给创建的实例属性赋值
* 3、将添加完类容的实体类添加到list集合中
*/
//list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
List<Map<String,Object>> list = new ArrayList<>();
//获取源数据
ResultSetMetaData md = rs.getMetaData();
int count = md.getColumnCount();
Map<String,Object> map = null;
while(rs.next()) {
map = new HashMap<>();
for (int i = 1; i <= count; i++) {
map.put(md.getColumnName(i), rs.getObject(i));
}
list.add(map);
}
return list;
}
});
}
}
RegionDao
package com.myy.dao;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.myy.util.JsonBaseDao;
import com.myy.util.JsonUtils;
import com.myy.util.PageBean;
import com.myy.util.StringUtils;
public class RegionDao extends JsonBaseDao {
public List<Map<String, Object>> list(Map<String,String[]> paramMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String id = JsonUtils.getParamVal(paramMap, "ID");
String sql = "select * from ch_region where true";
if(StringUtils.isBlank(id)) {
sql += " and parent_id=7459";
}else {
sql += " and parent_id="+id;
}
return super.executeQuery(sql, pageBean);
}
public static void main(String[] args) {
Map<String,String[]> paramMap = new HashMap<>();
paramMap.put("ID", new String[] {"9504"});
RegionDao regionDao = new RegionDao();
try {
List<Map<String, Object>> list = regionDao.list(paramMap, null);
System.out.println(list);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
JsonUtil(专门用来处理Jon数据的工具包1)
package com.myy.util;
import java.util.Arrays;
import java.util.Map;
/**
* 专门用来处理json数据的工具包
* @author Administrator
*
*/
public class JsonUtils {
/**
* 从paramMap拿到咱们所需要用到的查询维度,用于sql语句拼接
* @param paramMap获取从jsp页面传递到后台的参数集合(req.getParamterMap)
* @param key
* @return
*/
public static String getParamVal(Map<String,String[]> paramMap, String key) {
if(paramMap != null && paramMap.size()>0) {
String[] vals = paramMap.get(key);
if(vals != null && vals.length > 0) {
String val = Arrays.toString(vals);
return val.substring(1, val.length()-1);
}
return "";
}
return "";
}
}
RegionServlet
package com.myy.web;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myy.dao.RegionDao;
import com.myy.util.ResponseUtil;
public class RegionServlet extends HttpServlet {
private static final long serialVersionUID = 2174029632039137855L;
private RegionDao regionDao = new RegionDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
List<Map<String, Object>> list = regionDao.list(req.getParameterMap(), null);
ObjectMapper om = new ObjectMapper();
try {
ResponseUtil.write(resp, om.writeValueAsString(list));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
}
ResponseUtil
package com.myy.util;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
public class ResponseUtil {
public static void write(HttpServletResponse response,Object o)throws Exception{
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(o.toString());
out.flush();
out.close();
}
}
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>my_jQuery</display-name>
<servlet>
<servlet-name>regionServlet</servlet-name>
<servlet-class>com.myy.web.RegionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>regionServlet</servlet-name>
<url-pattern>/regionServlet</url-pattern>
</servlet-mapping>
</web-app>
jsp 页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/demo10.js"></script>
<title>Insert title here</title>
</head>
<body>
<div>
<input type="hidden" id="ctx" value="${pageContext.request.contextPath }">
<h1>$.ajax实现省市联动</h1>
<div>
收货地址
<select id="province">
<option selected="selected">---请选择省份---</option>
</select>
<select id="city">
<option selected="selected">---请选择城市---</option>
</select>
<select id=" county">
<option selected="selected">---请选择县区---</option>
</select>
</div>
</div>
</body>
</html>
运行结果: