Project structure:
Project run:
Technical points:
1.4.1 Technical Points
Before analyzing the specific implementation code, let's introduce some of the technical points of this example.
1. Dynamic creation and deletion of options
The CreateElement method of the Document object can be used to create an HTML element. Creating a good element can be done by
The SetAttribute method sets its properties. Based on the above two points, create an option to encapsulate the following methods:
function Createoption (value, text) {
var opt = document.createelement ("option"); Create an option node
Opt.setattribute ("value", value); Set Value
Opt.appendchild (document.createTextNode (text)); Adding text information to a node
return opt;
}
When you clear the option for a select list, you only need to reset the option's Length property to the appropriate value. In this case, keep
The 1th option of the list, so the passed-in list object is assigned a value of 1 for the length property.
function Clearoptions (selnode) {
Selnode.length = 1; Set the list length to 1, leaving only the default options
Selnode.options[0].selected = true; Select the default option
}
2. Reinitialize all subordinate lists when modifying a parent list
When the multilevel menu is all selected, if the user has re-selected the first level list, all of its downlevel lists need to be initialized.
To achieve this, this example creates a global variable, Selarray, that stores the IDs of the menu levels from top to bottom in an array form. In the need
To initialize a subordinate of a level list, the array is traversed to confirm the ID of the subordinate list.
3. Passing option data using JSON format
JSON (JavaScript Object Notation) is a simple way to format text with JavaScript object symbols. Because of its
Easy to read, easy to machine parse and generate, so it is mainly used as a lightweight data interchange format. JSON Master
There are two types of data structures to support: a name/value pair collection and a list of ordered values. The following is a detailed description of JSON supported data
Elements.
--Value: a string (string), number, Boolean, object, array, and so on, which can be enclosed in double quotation marks. Shown
For example the following:
"Hello"
2006
True
--Name/value pairs: The name is a string followed by a ":" followed by the name corresponding to the value, each "name
The name/value "pair is separated by a", ". Examples are as follows:
Figure 1.10 Example Run effect
"Hello": "Hi",
"Year": 2006,
"Isright": True
--object: Ends with "{", "}", and is an unordered set of "name/value" pairs. Examples are as follows:
{
"Hello": "Hi",
"Year": 2006,
"Isright": True
}
--array: Ends with "[", "]", is an ordered set of values, and the values in the array are separated by ",". Examples are as follows:
[
"Item1",
"Item2",
"Item3"
]
According to the above, it is found that the content of each option can be conveniently represented by the form of a name/value pair. Examples are as follows:
--Option Original format
<select>
<option value= "B11" > List B options 11</option>
<option value= "B12" > List B options 12</option>
<option value= "B13" > List B options 13</option>
</select>
--JSON format
{
' B11 ': ' list B option 11 ',
' B12 ': ' list B option 12 ',
' B13 ': ' list B option 13 '
}
As you can see, using the JSON format to represent option data is straightforward, easy to understand, and ideal for exchanging data.
Database:
/*sqlyog Ultimate v12.09 (+ bit) mysql-5.5.53:database-ajaxexample_4********************************************** *!40101 set NAMES UTF8 */;/*!40101 set sql_mode= ' */;/*!40014 set @[email protected]@ Unique_checks, unique_checks=0 */;/*!40014 SET @[email protected] @FOREIGN_KEY_CHECKS, foreign_key_checks=0 */;/ *!40101 set @[email protected] @SQL_MODE, sql_mode= ' No_auto_value_on_zero ' */;/*!40111 set @[email Protected] @SQL_NOTES, sql_notes=0 */; CREATE DATABASE/*!32312 IF not exists*/' ajaxexample_4 '/*!40100 DEFAULT CHARACTER SET UTF8 */; Use ' ajaxexample_4 ',/*table Structure for table ' menu ' */drop Table IF EXISTS ' menu '; CREATE TABLE ' menu ' (' id ' varchar (255) NOT NULL COMMENT ' primary key ', ' text ' varchar (255) NOT NULL COMMENT ' display content ', ' pid ' Varch AR (255) NOT null default ' 0 ' COMMENT ' parent id ', ' sort ' int (one) not null default ' 0 ' COMMENT ' sort ', PRIMARY KEY (' id ')) ENGINE =innodb DEFAULT charset=utf8;/*data for the table ' menu ' */insert into ' menu ' (' id ', ' text ', ' pid ', ' Sort ') values (' A1 ', ' A1 ', ' 0 ', 0), (' A2 ', ' A2 ', ' 0 ', 0), (' A3 ', ' A3 ', ' 0 ', 0), (' B1 ', ' B1 ', ' A1 ', 0), (' B2 ', ' B2 ', ' A1 ', 0), (' B3 ', ' B3 ', ' A1 ', 0), (' B4 ', ' B4 ', ' A2 ', 0), (' B5 ', ' B5 ', ' A2 ', 0), (' B6 ', ' B6 ', ' A2 ', 0), (' B7 ', ' B7 ', ' A3 ', 0), (' B8 ', ' B8 ', ' A3 ', 0), (' C1 ', ' C1 ', ' B1 ', 0), (' C2 ', ' C2 ', ' B1 ', 0), (' C3 ', ' C3 ', ' B2 ', 0), (' C4 ', ' C4 ', ' B3 ', 0), (' C5 ', ' C5 ', ' B4 ', 0 ), (' C6 ', ' C6 ', ' B4 ', 0);/*!40101 set [Email protected]_sql_mode */;/*!40014 set [Email protected]_foreign_ Key_checks */;/*!40014 Set [email protected]_unique_checks */;/*!40111 set [Email protected]_sql_notes *;
Getoptionservlet.java:
Package Com.gordon.servlet;import Java.io.ioexception;import Java.sql.connection;import java.sql.PreparedStatement ; Import Java.sql.resultset;import Java.sql.sqlexception;import Javax.servlet.servlet;import Javax.servlet.servletconfig;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.gordon.util.dbutils;/** * Servlet Implementation class Getoptionsservlet */@WebServlet ("/getoptionsservlet") public class Getoptionsservlet extends HttpServlet {private Static final Long Serialversionuid = 1l;/** * @see httpservlet#httpservlet () */public Getoptionsservlet () {super ();//TODO Auto-generated Constructor stub}/** * @see servlet#init (servletconfig) */public void init (servletconfig config) throws Se rvletexception {//TODO auto-generated method stub}/** * @see httpservlet#doget (httpservletrequest request, HttpServletResponse * Response) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {request.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/text; Charset=utf-8; "); String Selectedid = Request.getparameter ("Selectedid"); Gets the selectedid//parameter int counter = 0; Counter StringBuffer opts = new StringBuffer ("{"); Save option Information//define SQL statement to query database string sql = "Select * from menu where pid =?" ORDER by sort ASC "; Connection conn = null; Declares the Connection object preparedstatement pstmt = null; Declares the PreparedStatement object resultset rs = null; Declare ResultSet object try {conn = dbutils.getconnection ();//Get database connection pstmt = conn.preparestatement (sql);//create Prepared based on SQL Statementpstmt.setstring (1, Selectedid); Set Parameter rs = Pstmt.executequery (); Executes the query, returns the result set while (Rs.next ()) {//iterates over the result set//If it is not the first item, appends a "," to delimit the option if (Counter > 0) {opts.append (",");} Opts.append ("'"); Opts.append (rs.getstring ("id")); Opts.append ("': '"); Opts.append (rs.getstring ("text")); O Pts.append ("'"); counter++; Counter plus 1}} catch (SQLException e) {System.out.println (e.tostring ());} catch (ClassNotFoundException Cnfe) { System.out.println (Cnfe.tostring ());} try {rs.close ();//close result set pstmt.close ();//close Preparedstatementconn.close ();//Close connection} catch (Exception e) {System.out.prin TLN (E.getmessage ());} Opts.append ("}"); Response.getwriter (). Print (opts.tostring ());} /** * @see Httpservlet#dopost (httpservletrequest request, HttpServletResponse * response) */protected void DoPost (HTT Pservletrequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated Method Stubdoget (Request, Response);}}
Dbutils.java
Package Com.gordon.util;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.SQLException; public class Dbutils {private static final String URL = "Jdbc:mysql://localhost:3306/ajaxexample_4";p rivate static final S Tring DRIVER = "Com.mysql.jdbc.Driver";p rivate static final String USERNAME = "root";p rivate static final string PASSWORD = "root";p ublic static Connection getconnection () throws ClassNotFoundException, SQLException {class.forname (DRIVER); Return Drivermanager.getconnection (URL, USERNAME, PASSWORD);}}
Select.js
var xmlHttp; The global variable var targetselid used to hold the XMLHttpRequest object; The list to save the options to update Idvar Selarray; Array to hold the cascading menu ID//Initialize list array (by rank) function Initselarray () {selarray = arguments;//Arguments object contains all parameters passed in}//used to create Xmlhttpre Quest Object Function Createxmlhttp () {//according to window. XMLHttpRequest whether the object exists using a different creation method if (window. T.xmlhttp "); IE Browser Support creation method}}//get list option call function Buildselect (Selectedid, Targetid) {if (Selectedid = = "") {//Selectedid as empty string indicates selected Default item Clearsubsel (Targetid); Clears the destination list and the options in the subordinate list return; End call directly, do not need to request information to the server}targetselid = Targetid; Assigns the ID of the incoming target list to the Targetselid variable createxmlhttp (); Create XMLHttpRequest Object xmlhttp.onreadystatechange = Buildselectcallback; Set the callback function Xmlhttp.open ("GET", "getoptionsservlet?selectedid=" + Selectedid, True); Xmlhttp.send (null);} Creates an option based on the value and text passed in, function createoption (value, text) {var opt = document.createelement ("option");//Create one optionNode Opt.setattribute ("value", value); Set Valueopt.appendchild (document.createTextNode (text)); Add text message to node return opt;} Gets the list option of the callback function Buildselectcallback () {if (xmlhttp.readystate = = 4) {//To convert the text obtained from the server to the direct amount of the object var optionsinfo = eval ("( "+ Xmlhttp.responsetext +"); var Targetselnode = document.getElementById (targetselid); Clearsubsel (targetSelId); Clear the target list and the options in the Subordinate list//traverse the object directly in the amount of the member for (Var o in optionsinfo) {//Append a new option to the target list targetselnode.appendchild (Createoption (O, Optionsinfo[o]));}}} Clears all options in the Incoming List node function clearoptions (selnode) {selnode.length = 1;//Set list length to 1, leaving only the default option selnode.options[0].selected = True Select the default option}//clear subordinate Sub-list option function Clearsubsel (targetid) {var canclear = false;//set purge switch, initial value is False for (var i = 0; i < Selarray . length; i++) {//Traversal list array if (selarray[i] = = Targetid) {//when traversing to the target list, turn on the purge switch canclear = true;} if (canclear) {//from the target list to the end of the sub-list, the switch remains open clearoptions (document.getElementById (Selarray[i]));//Clear the Level list option}}}
index.jsp
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >+++++++++++++++++++++++++++
Reference: Ajax Utility Case Daquan-1 dynamic load Data https://wenku.baidu.com/view/c7897bf4700abb68a982fb91.html
Ajax-ajax Instance 4-Multi-level linkage menu