jQuery基础2

目录

jquery动画

js的遍历方式

jquery事件绑定

jquery自定义jquery方法

原始ajax

在servlet里

jQuery仿百度搜索下拉框

首页

servlet里

list.jp页面

jquery省市联动

首页

servlet里

采用json传输数据

在servlet里

在页面接受json数据的jquery代码


前言

jQuery基础(1)  https://blog.csdn.net/yzj17025693/article/details/95438320

jQuery基础(3)    https://blog.csdn.net/yzj17025693/article/details/88420097 

jquery动画

js的遍历方式

原始方式

jquery的方式

在function里写上index和element,当然也可以用this

element默认是原生的js对象

全局遍历方式

for...of方式(jquery 3.0以后才支持)

jquery事件绑定

链式编程

如果off不写参数,那么就是解除所有事件

jquery自定义jquery方法

原始ajax

ajax最大的用处就是异步请求,异步和同步的区别请去百度.前部分是纯ajax的,后面部分会有jquery的ajax

如果想深入了解 https://blog.csdn.net/u013766533/article/details/52314519

简单的来说 ajax可以在不重新加载整个页面的情况下,与服务器交换数据。这种异步交互的方式,使用户单击后,不必刷新页面也能获取新数据

纯ajax校验用户名

<%@ 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">
<title>Insert title here</title>
 
<script type="text/javascript">
 
	function ajaxFunction()
	{
		 var request;
		if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
			request = new XMLHttpRequest();
		} else {// code for IE6, IE5
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		return request
	}
	 
	function  checkUser()
	{
		
		//获取输入框的数值
		var username= document.getElementById("username").value;
		
		//获取到ajax对对象
		 var request=ajaxFunction();
		 
		 //这个true代表异步
		 request.open("POST","_002_",true);
		 
// 		 获取响应的消息,onreadystatechange是状态发生改变的事件,当服务器发送了消息回来
// 		 这个事件就会触发. 
		 request.onreadystatechange=function()
		 {
			if(request.readyState==4 && request.status==200)
		    {
				//responseText储存的是服务器发过来的消息,还有很多request参数看文档
				if(request.responseText==1)
				{
					document.getElementById("span1").innerHTML="<font color='red'>用户名已存在!</font>"
				}
				else
				{
					document.getElementById("span1").innerHTML="<font color='green'>用户名可用!</font>"	  
				}
		    }
			 
		 }
 
		 //post方式需要设置请求头
		 request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 
		 
		 //发送用户名过去
		 request.send("username="+username);
}
	 
</script>
 
</head>
<body>
		<table>
		  <tr>
			 <td>用户名: </td>    
             <!--这里失去焦点就会去执行函数-->
			 <td><input type="text" name="username" id="username" οnblur="checkUser()"/>
			 <span id="span1"></span>
			 </td>
		  </tr>
	  </table>
 
</body>
</html>

在servlet里

接受数据,并且校验,然后写出状态,这是最原始的服务器校验

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		//解决接收乱码问题
		request.setCharacterEncoding("utf-8");

		// 获取用户名并且判断
		String name = request.getParameter("username");
		
		//这里应该是从数据库里查询并判断
		boolean isExist =true; 

		// 设置输出编码
		response.setContentType("text/html;setchar=utf-8");
		if (isExist)
		{
			// 写成状态,1代表用户名存在,2代表不存在,可以注册
			response.getWriter().println(1);
		} else
		{
			response.getWriter().println(2);
		}

	}

jQuery仿百度搜索下拉框

首页

当按键弹起后,便会向后台发送post异步请求

<html>
<head>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function(){
	//按键按下了之后,就去发生请求
   $("#words").keyup(function(){
		//获取输入框的值
		var word=$(this).val();
		
		if(word=="")
		{
			$("div1").hide();
		}else
		  {
		  	//请求数据
			$.post("test",{word:word},function(data,status){
		    		$("#div1").show();
		    		
		    		//把页面数据全部放入
		    		$("#div1").html(data);
			 });
		  }

	});
})
</script>

</head>
<body>
	<center>
		<h2>天帝</h2>
<!-- 		 输入框 -->
		<input type="text" name="words" id="words" style="width: 600px; height: 50px; font-size: 20px;">
		<!-- 			这个按钮目前装饰用  -->
		<input type="button" value="搜索一下" style="height: 55px; width: 100px;">

		<!-- 			
		position: relative; left: -54px 是相对定位,且需要display:noe先隐藏结果栏
		 -->
		<div id="div1"
			style="position: relative; left: -54px; width: 600px; height: 200px; border: 1px solid blue; display: none">
		</div>
		
	</center>
</body>
</html>

servlet里

servlet处理了请求后便会转发list.jsp页面,因为是转发,而请求又是异步的,所以相当于把整个list.jp页面传给了上面的data

这时候相当于在一个div里嵌套了一个页面,也就是那个"下拉框"

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
	     try
		{
		//获取关键词参数
		String word=request.getParameter("word");
		
		//执行查询,这里不是关键,使用的是DBUtils,JDBCUtil.getDataSource我们自己写的工具类,用于获取数据源
		QueryRunner runner=new QueryRunner(JDBCUtil.getDataSource());
		String sql="select * from word where words like ?";
		List<WordBean>list=runner.query(sql, new BeanListHandler<WordBean>(WordBean.class),word+"%");
			
		//返回数据
		request.setAttribute("list", list);
		response.setContentType("text/html;charset=utf-8");
		request.getRequestDispatcher("list.jsp").forward(request, response);
			
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
		
	}

list.jp页面

遍历存放到list里的数据

<body>
<table style="100%">
	<c:forEach items="${list}" var="wordBean">
		<tr>
			<td>${wordBean.words}</td>
		</tr>
	</c:forEach>
</table>
</body>

jquery省市联动

会用到jQuery遍历和查找的知识

首页

绑定change事件,切换省之后,就会发送ajax请求,发送数据回来

接受的是xml数据(也可以是json),然后搜索指定节点,搜索完后遍历这个节点的所有数据

加入到select里

<html>
  <head>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
  <script type="text/javascript">
   $(function(){
	// 一旦里面的值发生了改变,那么就去请求该省份的城市数据
  	$("#province").change(function(){
		var pid=$(this).val();	
		
  		//发送请求,请求城市数据
  		$.post("test",{pid:pid},function(data,status){
  				//先清理以前的值
  				$("#city").html("<option value=''>-请选择-"+"</option>")
  				
  				//遍历数值,返回的是一个list
  				//find找出所有包含city的节点
  				//each是遍历每个节点
  				$(data).find("city").each(function(){
  					//children只查找第一个节点,我们也只有一个属性叫id,又不能重复
  					var id=$(this).children("id").text();
  					var cname=$(this).children("cname").text();
  					$("#city").append("<option value='"+id+"'>"+cname+"</option>");
  				});
  		});
  	});
 });
  	
  </script>
  
  </head>
  
  <body>
  省份: 
  <select name="province"  id="province">
			 <option value="">=请选择=</option>
			 <option value="1">广东</option>
			 <option value="2">四川</option>
  			</select>
  
  城市:
  <select name="city" id="city">
  			<option value="">选择</option>
  </select>
  
  </body>
</html>

发送回来的xml数据格式

servlet里

采用XStream把bean转换为xml数据

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		try
		{
			//获取pid
			int pid=Integer.parseInt(request.getParameter("pid"));
			System.out.println(pid);
			
			
			//根据找出所有城市
			QueryRunner runner=new QueryRunner(JDBCUtil.getDataSource());
			String sqlString="select * from city where pid=?";
			List<CityBean >list=runner.query(sqlString, new BeanListHandler<CityBean>(CityBean.class),pid);
			
			//返回城市数据
			//城市的数据包含名称和id,而且有多个城市,客户端需要遍历一个一个添加到下拉框里
			//所以这里可以返回一个xml数据(json也行)
			//使用XStream把bean对象转换成xml
			XStream xStream=new XStream();
			
			//id做成节点属性
			xStream.useAttributeFor(CityBean.class,"id");
			
			//设置别名,把CityBean变成city作为节点的名称
			xStream.alias("city", CityBean.class);
			
			//把对象转换成xml字符串
			String xml= xStream.toXML(list);
			
			System.out.println(xml);
			
			//设置输出类型为text/xml
			response.setContentType("text/xml;charset=UTF-8");
			response.getWriter().write(xml);
			
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

采用json传输数据

这里使用的是Json-lib

在servlet里

要注意的是这里使用的是json-lib,把list集合转换为json数据

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
			try
			{
				//获取pid
				 int pid=Integer.parseInt(request.getParameter("pid"));
				 System.out.println(pid);
				 
				 //查找所有城市
				 CityDao dao=new CityDaoImp();
				 List<CityBean> list=dao.findCity(pid);
				 
				 //把list对象转换成json数组形式
				 //JSONArray   把数组,集合转换为json
				 //JsonArray     把单一对象和map集合转换为json
				 JSONArray jsonArray=JSONArray.fromObject(list);
				 
				 //把数组转换成字符串
				 String json=jsonArray.toString();
				 
				 System.out.println(json);
				 
				 //把json数据写出去
				 response.setContentType("text/html;charset=utf-8");
				 response.getWriter().write(json);
				 
			} catch (Exception e)
			{
				e.printStackTrace();
			}
	}

在页面接受json数据的jquery代码

$(function(){
	
	//省份被选择,那么市下拉框就会改变
	 $("#province").change(function(){
		 	//取得省的id
		    var pid2 =$(this).val();
		    
		    //post有3个参数,最后一个是要解析的格式,如果我们写的是json
		    //可以需要自己填写一下,其他情况应该都是自动解析的
		    $.post("test",{pid:pid2},function(data,status){
		    
		    	//先清空以前的数值
		    	$("#city").html("<option value=''>=请选择=</option>");
		    	//遍历json数据
		    	//为何和xml格式的的不一样,这个看文档可知,xml格式用的是省略参数的
		    	//参数1是索引,参数2是当前元素,就是this
		    	$(data).each(function(index,element1){
		    		
		    		 $("#city").append("<option value=''>"+element1.cname+"</option>")
		    		
		    	});

		    //这里一定要指定json
		    },"json");
	 });
});
发布了143 篇原创文章 · 获赞 36 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/yzj17025693/article/details/95490855