今天是复习jQuery的最后一天,基本常用技术已全部练习,以后遇到不会的可查文档。总的来说,jQuery的出现,在写前端代码时省事了好多。
one.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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="<c:url value='/js/jquery-3.1.0.js' />"></script>
<title>jQuery技术实例</title>
<script type="text/javascript">
$(function(){
$("#btn1").click(function(){
//jQuery-ajax的get方法是不能传递中文的参数,否则会乱码
var url="<c:url value='/Servlet1' />";
$.get(url,{"name":"AA中文","age":22},function(data,textStatus,xhr){
alert(data+","+textStatus);
});//格式:jQuery.get(url, [data], [callback], [type]) 最后一个参数为空
});
$("#btn2").click(function(){
//jQuery-ajax的普通post方法是可以传递中文参数
var url="<c:url value='/Servlet1' />";
$.post(url,{"name":"AAAA中文","age":22},function(data,textStatus,xhr){
alert(data+","+textStatus);//可正常显示后台发来的信息
});//格式:jQuery.post(url, [data], [callback], [type]) 最后一个参数为空
});
$("#btn3").click(function(){
//jQuery-ajax的post---xml方法通信
var url="<c:url value='/Servlet1' />";
$.post(url,{"name":"AAAA中文","age":22},function(data,textStatus,xhr){
//alert(data+","+textStatus);//object XMLDocument
//jQuery来解析xml格式的dom对象
//<users><user id='U001'><name>jack1</name><name>jack2</name></user><user id='U002'><name>Tom</name></user></users>"
$(data).find("user").each(function(){
//for循环遍历 获取当前user对象的id
var id=$(this).attr("id");
//alert(id);
//获取当前<user>的name
var name=$(this).find("name:eq(0)").text();//这种方式能实现一个user中有两个name,只显示一个name
alert(id+","+name);
});
},"xml");//post方法最后一个参数表示通信方式返回内容格式,xml, html, script, json, text, _default。
});
$("#btn4").click(function(){
//jQuery-ajax的post---json方法通信技术
var url="<c:url value='/JsonServlet3' />";
$.post(url,{"name":"AAAA中文","age":22},function(data,textStatus,xhr){
//alert(data); //json-object 有很多object(这里是user对象)
$(".d").empty();//先清空已经显示的内容
$.each(data,function(idx,val){
$(".d").append(idx+":"+val.id+","+val.name+","+val.age+"<br/>");
});
},"json");//指定json通信
});
});
</script>
</head>
<body>
<button id="btn1">jQuery-ajax的get方法技术</button><br/>
<button id="btn2">jQuery-ajax的post方法技术</button><br/>
<button id="btn3">jQuery-ajax的post---xml方法通信技术</button><br/>
<button id="btn4">jQuery-ajax的post---json方法通信技术</button><br/>
<div class="d"></div>
<br/><hr/>
<a href="<c:url value='/MenuServlet' />">点击进入动态(从数据库)加载二级菜单 jQuery中ajax.load()方法</a>
</body>
</html>
Servlet1.java
package cn.hncu.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get方式的请求来了....");//不支持中文
String name = request.getParameter("name");
String age = request.getParameter("age");
System.out.println("name:"+name+",age:"+age);
response.setContentType("text/html;charset=utf-8");
String str ="<users><user id='U001'><name>jack</name></user>"
+ "<user id='U002'><name>Tom</name></user></users>";
response.getWriter().print(str);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post方式的请求来了....");
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
System.out.println("name:"+name+",age:"+age);
response.setContentType("text/html;charset=utf-8");
String str ="<users><user id='U001'><name>jack1</name><name>jack2</name></user>"
+ "<user id='U002'><name>Tom</name></user></users>";
response.getWriter().print(str);
}
}
JsonServlet3
package cn.hncu.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import cn.hncu.domain.User;
@WebServlet("/JsonServlet3")
public class JsonServlet3 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post-json方式的请求来了....");
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
System.out.println("name:"+name+",age:"+age);
//按理应该调用service、dao层并从数据库中把数据读取出来,这里模拟了...
List<User> users = new ArrayList<User>();
users.add( new User("U001","Jack",22));
users.add( new User("U010","张三",12));
users.add( new User("U002","Rose",23));
request.setAttribute("users", users);
//利用fastjson的工具为我们把后台的List<User>类型的数据封装成json格式串,发送前端
//json串格式: [{name:"Jack",id:"U001",age:22},{...},{...}]
//转List-json※※※
String json = JSON.toJSONString(users);
System.out.println("json:"+json);
//转Map-json
Map<String, Object> map = new HashMap<String, Object>();
map.put("addr", "湖南");
map.put("id", "P001");
map.put("sex", "男");
map.put("age", 20);
map.put("friend", new User("U001","Jack",22));
String str = JSON.toJSONString(map);
System.out.println(str);
//发给前端
response.setCharacterEncoding("utf-8");
response.getWriter().print(json);
}
}
这里是实现了ajax get和post通信,jQuery中有封装好的的ajax通信,直接调用方法即可,不再用写底层代码了。
MenuServlet.java
注:此处用到了C3p0和QueryRunner,它的配置文件和工具类这里就不再贴出了。以前的博客有详细介绍。
package cn.hncu.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import cn.hncu.domain.Menu;
import cn.hncu.utils.DataSourceUtils;
import cn.hncu.utils.QueryRunner;
@WebServlet("/MenuServlet")
public class MenuServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//查询出所有一级菜单
String sql="select * from menus where parent is null";
QueryRunner run=new QueryRunner(DataSourceUtils.getDataSource());
List<Menu> menus=run.query(sql, new BeanListHandler<Menu>(Menu.class));
System.out.println(menus);
request.setAttribute("menus", menus);
request.getRequestDispatcher("/three/two.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//加载主菜单下面的二级菜单
String id=request.getParameter("pid");
String sql="select * from menus where parent="+id;
QueryRunner run=new QueryRunner(DataSourceUtils.getDataSource());
List<Menu> menus=run.query(sql, new BeanListHandler<Menu>(Menu.class));
request.setAttribute("subMenus", menus);
request.getRequestDispatcher("/three/three.jsp").forward(request, response);
}
}
two.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
#menu{
border: 1px solid red;
width: 40%;
background:gray;
margin:3px;
cursor:pointer;
}
.main{
height:60px;
background:gray;
border: 1px solid blue;
width: 20%;
margin:15px;
cursor: pointer;
}
.sub{
background:yellow;
width: 40%;
margin:3px;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="<c:url value='/js/jquery-3.1.0.js' />"></script>
<title>jQuery技术实例</title>
<script type="text/javascript">
$(function(){
$(".main").click(function(){
var sub=$(this).next(".sub");
if(sub.length>0){
sub.toggle();
}else{
var subDiv=$("<div class='sub' >AAAA</div>");//利用jQuery核心函数创建出一个jQuery对象,然后调用jQuery中的函数
var url="<c:url value='/MenuServlet' />";
var id=$(this).attr("id");
subDiv.load(url,{pid:id});//把通过load加载的内容放到subDiv中
$(this).after(subDiv);//加在主菜单后面----兄弟关系
}
});
});
</script>
</head>
<body>
<b>以下是菜单</b>
<div id="menu">
<c:forEach items="${menus}" var="menu">
<div class="main" id="${menu.id}">
<p align="center">${menu.name}</p>
</div>
</c:forEach>
</div>
</body>
</html>
three.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach items="${subMenus}" var="menu">
<a href="<c:url value='${menu.url}'/>">${menu.name}</a> <br/>
</c:forEach>
sql记录
CREATE TABLE menus(
id INT PRIMARY KEY,
NAME VARCHAR(30),
parent INT,
url VARCHAR(100)
);
INSERT INTO menus VALUES(1,"管理员",NULL,NULL);
INSERT INTO menus VALUES(2,"一般管理员",NULL,NULL);
INSERT INTO menus VALUES(3,"管理用户",1,'/jsps/1.jsp');
INSERT INTO menus VALUES(4,"管理图书",1,'/BookSevlet');
INSERT INTO menus VALUES(5,"管理订单",2,'/BookSevlet');
INSERT INTO menus VALUES(6,"管理出货",2,'/BookSevlet');
这也算是一个小小的应用吧。可根据数据库中的记录来查找一级菜单和二级菜单。