The example in this article describes the method of linking jQuery jsp drop-down box to obtain local data. Share it with everyone for your reference, the details are as follows:
JQuery drop-down box linkage well reflects Ajax’s requirements for on-demand data acquisition and reduces the amount of data interaction. (Click here to download the source code )
The following example uses Json to convert server-side classes or objects into JSON format, mainly using 6 jar packages
commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-lang-2.3.jar
commons-logging-1.0.4.jar
ezmorph-1.0.3.jar
json-lib-2.1.jar
The experimental picture is attached below, and the main code is explained in detail
Display page index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>JQuery实例-级联下拉框效果</title> <meta http-equiv= "Content-Type" content="text/html";charset=UTF-8"> <link type="text/css" rel="stylesheet" href="css/chainselect.css" /> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/chainselect.js"></script> </head> <body> <div class="loading"> <p><img src="images/data-loading.gif" alt="jQuery jsp drop-down box linkage method to obtain local data (source code attached)_jquery" /></p> <p>jQuery jsp drop-down box linkage method to obtain local data (source code attached)_jquery......</p> </div> <div class="car"> <span class="carname"> 汽车厂商: <select> <option value="" selected="selected">请选择汽车厂商</option> <option value="BMW">宝马</option> <option value="Audi">奥迪</option> <option value="VW">大众</option> </select> <img src="images/pfeil.gif" alt="有数据" /> </span> <span class="cartype"> 汽车类型: <select></select> <img src="images/pfeil.gif" alt="有数据" /> </span> <span class="wheeltype"> 车轮类型: <select></select> </span> </div> <div class="carimage"> <p><img src="images/img-loading.gif" alt="图片装载中" class="carloading" /></p> <p><img src="images/BMW_316ti_rha.jpg" alt="汽车图片" class="carimg"/></p> </div> </body> </html>
Modify the file chainselect.css
.loading { width: 400px; /*margin-left: auto;*/ /*margin-right: auto;*/ margin: 0 auto; visibility: hidden; } .loading p { text-align: center; } p { margin: 0; } .car { /*width: 500px;*/ /*margin: 0 auto;*/ text-align: center; } .carimage { text-align: center; } .cartype, .wheeltype, .carloading, .carimg, .car img { display: none; }
Here, pay attention to the difference between the attributes display: none; and visibility: hidden;
display: none;
After using this attribute, the width, height and other attribute values of the HTML element (object) will be "lost";
visibility: hidden;
After using this attribute, the HTML element (object) is only visually invisible (completely transparent), but the spatial position it occupies still exists, that is to say, it still has attribute values such as height and width.
JQUERY processing file chainselect.js
$(document).ready(function(){ //找到三个下拉框 var carnameSelect = $(".carname").children("select"); var cartypeSelect = $(".cartype").children("select"); var wheeltypeSelect = $(".wheeltype").children("select"); var carimg = $(".carimg"); //给三个下拉框注册事件 carnameSelect.change(function(){ //1.需要获得当前下拉框的值 var carnameValue = $(this).val(); //1.1只要第一个下拉框内容有变化,第三个下拉框都要先隐藏起来 wheeltypeSelect.parent().hide(); //1.2将汽车图片隐藏起来 carimg.hide().attr("src",""); //2.如果值不为空,则将下拉框的值传送给服务器 if (carnameValue != "") { if (!carnameSelect.data(carnameValue)) { //对应服务器端程序 CarJsonServlet的属性,并将该Servlet中的数据转换为JSON格式 $.post("CarJsonServlet",{keyword: carnameValue, type: "top"},function(data){ //2.1接收服务器返回的汽车类型 ,data为数组格式 if (data.length != 0) { //2.2解析汽车类型的数据,填充到汽车类型的下拉框中 cartypeSelect.html(""); $("<option value=''>请选择汽车类型</option>").appendTo(cartypeSelect); for (var i = 0; i < data.length; i++) { $("<option value='" + data[i] + "'>" + data[i] + "</option>").appendTo(cartypeSelect); } //2.2.1汽车类型的下拉框显示出 cartypeSelect.parent().show(); //2.2.2第一个下拉框后面的指示图片显示出来 carnameSelect.next().show(); } else { //2.3没有任何汽车类型的数据 cartypeSelect.parent().hide(); carnameSelect.next().hide(); } carnameSelect.data(carnameValue, data); }, "json"); } } else { //3.如果值为空,那么第二个下拉框所在span要隐藏起来,第一个下拉框后面的指示图片也要隐藏 cartypeSelect.parent().hide(); carnameSelect.next().hide(); } }); cartypeSelect.change(function(){ //1.需要获得当前下拉框的值 var cartypeValue = $(this).val(); //1.1将汽车图片隐藏起来 carimg.hide().attr("src",""); //2.如果值不为空,则将下拉框的值传送给服务器 if (cartypeValue != "") { if (!cartypeSelect.data(cartypeValue)) { $.post("CarJsonServlet",{keyword: cartypeValue, type: "sub"},function(data){ //2.1接收服务器返回的汽车类型 if (data.length != 0) { //2.2解析汽车类型的数据,填充到车轮类型的下拉框中 wheeltypeSelect.html(""); $("<option value=''>请选择车轮类型</option>").appendTo(wheeltypeSelect); for (var i = 0; i < data.length; i++) { $("<option value='" + data[i] + "'>" + data[i] + "</option>").appendTo(wheeltypeSelect); } //2.2.1车轮类型的下拉框显示出 wheeltypeSelect.parent().show(); //2.2.2第二个下拉框后面的指示图片显示出来 cartypeSelect.next().show(); } else { //2.3没有任何汽车类型的数据 wheeltypeSelect.parent().hide(); cartypeSelect.next().hide(); } cartypeSelect.data(cartypeValue, data); }, "json"); } } else { //3.如果值为空,那么第三个下拉框所在span要隐藏起来,第二个下拉框后面的指示图片也要隐藏 wheeltypeSelect.parent().hide(); cartypeSelect.next().hide(); } }); wheeltypeSelect.change(function(){ //1.获取车轮类型 var wheeltypeValue = $(this).val(); //2.根据汽车厂商名称,汽车型号和车轮类型得到汽车图片的文件名 var carnameValue = carnameSelect.val(); var cartypeValue = cartypeSelect.val(); var carimgname = carnameValue + "_" + cartypeValue + "_" + wheeltypeValue + ".jpg"; //3.显示出loading的图片 carimg.hide(); $(".carloading").show(); //4.通过Javascript中的Image对象预装载图片 var cacheimg = new Image(); $(cacheimg).attr("src","images/" + carimgname).load(function(){ //隐藏loading图片 $(".carloading").hide(); //显示汽车图片 carimg.attr("src","images/" + carimgname).show(); }); //3.修改汽车图片节点的src的值,让汽车图片显示出来 //carimg.attr("src","images/" + carimgname).show(); //4.使汽车图片的节点显示出来 }); //给jQuery jsp drop-down box linkage method to obtain local data (source code attached)_jquery的节点定义ajax事件,实现动画提示效果 $(".loading").ajaxStart(function(){ $(this).css("visibility","visible"); $(this).animate({ opacity: 1 },0); }).ajaxStop(function(){ $(this).animate({ opacity: 0 },500); }); })
Question? ? ? :$("").appendTo(cartypeSelect);How to solve the Chinese garbled characters here? ? ?
Server-side CarJsonServlet
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; public class CarJsonServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决中文乱码 response.setHeader("Cache-Control", "no-cache"); response.setContentType("text/json;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); //得到type,keyword的值 String type = request.getParameter("type"); String keyword = request.getParameter("keyword"); JSONArray jsonArrayResult = new JSONArray(); if ("top".equals(type)) { if ("BMW".equals(keyword)) { jsonArrayResult.add("316ti"); jsonArrayResult.add("6ercupe"); } else if ("Audi".equals(keyword)) { jsonArrayResult.add("tt"); } else if ("VW".equals(keyword)) { jsonArrayResult.add("Golf4"); } } else if ("sub".equals(type)) { if ("tt".equals(keyword)) { jsonArrayResult.add("rha"); jsonArrayResult.add("rhb"); jsonArrayResult.add("rhc"); } else if ("316ti".equals(keyword)) { jsonArrayResult.add("rha"); jsonArrayResult.add("rhb"); } else if ("6ercupe".equals(keyword)) { jsonArrayResult.add("rha"); jsonArrayResult.add("rhb"); jsonArrayResult.add("rhc"); } else if ("Golf4".equals(keyword)) { jsonArrayResult.add("rha"); jsonArrayResult.add("rhb"); } } PrintWriter out = response.getWriter(); out.write(jsonArrayResult.toString()); out.flush(); out.close(); } }
Configuration file web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <servlet> <servlet-name>CarJsonServlet</servlet-name> <servlet-class>CarJsonServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CarJsonServlet</servlet-name> <url-pattern>/CarJsonServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
JQuery and other development knowledge learned in this section:
1. The alt attribute of the img tag should be written. When the image has not been loaded or the image does not exist, the text information of this attribute will be displayed
2.select represents a drop-down box. Each item in the drop-down box is an option. The content in the option start and end tags will be displayed on the page. The value of the value attribute is used to obtain and send to the server using the val method in JQuery. of. When the attribute value of selected is defined as selected, it means that the current option is selected
3. How to display the div element in the center: set the width of the div, and then the values of margin-left and margin-right are both auto. The abbreviation is margin: 0 auto;
4. The p tag of html represents the content of a paragraph. The content will occupy one or more lines, and the following content will be displayed on another line
5. In order to center the text and pictures in p, you can use the text-align attribute, and the attribute value is center. The p tag has margin-top and margin-bottom values by default, which can be cleared through css if necessary
6. When the visibility attribute value is hidden, the element is hidden, but unlike display, which is none, it still occupies a certain space on the page, but
is not displayed.
7. If multiple selectors have the same attribute value, they can be defined together and separated by commas
8. The change method corresponds to the onchange event in standard Javascript and can handle events when the content of the drop-down box changes
9.The parent method can obtain the parent node of a node
10. The next method can get the next sibling node of a node, and the corresponding previous method can get the previous sibling node of a node
11. The $.post method can initiate an asynchronous post request with the server. The first parameter is the server-side address of the request, the second parameter is the data sent to the server, the parameter is a Javascript object, expressed in the form of name-value pairs, the third parameter is the callback method, and the fourth parameter indicates the server The data type returned by the end, JQuery will help us convert according to this parameter. The get method only differs in the second parameter, and the other parameters have the same usage
12.The simple object definition method in Javascript is {key1: value1, key2: value2}
13. The data format of JSON is actually the text format content defined by an object or data in Javascript, such as {key1: value1, key2: [1,2,3]} or [1,2,{key2:
value2}]
14. You can directly use the $("") method to create the options in the drop-down box, and then use the appendTo method to add them to the drop-down box
15. The attr method can set or get the attribute value of a node
16.ajaxStart is executed before each ajax request issued by JQuery starts, ajaxStop is executed after all ajax requests in the JQuery queue are completed, and ajaxComplete is executed after each ajax request issued by JQuery is completed
17. fadeOut and fadeIn can achieve the effect of fade out and fade in. The parameter content is similar to the slideUp and slideDown methods.
18. The animate method can achieve any animation effect and can control a certain css attribute to change within a certain period of time to achieve the animation effect
19.Opacity can change the transparency of elements. In IE, a filter is used to implement it. 100 means fully displayed and 0 means completely transparent. Non-IE browsers use the opacity attribute. 1 means fully displayed and 0 means transparent. JQuery blocks browser differences in the animate method, and you can use opacity directly to achieve the fade-in and fade-out effect.
20. The data method can be used to cache data. Caching can improve the operating efficiency of the system and reduce the load on the server
21. You can use the Image object in Javascript to preload images, so that you can know when the image is loaded, so that you can give some prompt information for image loading.
22. The load method can correspond to the onload event in Javascript. In this example, it is used to capture the event that the image is loaded
I hope this article will be helpful to everyone in jQuery programming.