Example of second-level interaction in the drop-down box using Ajax and Jquery combined with the database, ajaxjquery

Source: Internet
Author: User

Example of second-level interaction in the drop-down box using Ajax and Jquery combined with the database, ajaxjquery

First, we need to set up a database to insert some data into it.

Two tables are required:

Province: province table

City: city table

Then, create the corresponding object classes in java.

Then, we can start the jdbc operation.

Public class ConnectionFactory {private static String driver; private static String url; private static String user; private static String password; static {Properties prop = new Properties (); // read the file try {InputStream in = ConnectionFactory. class. getResourceAsStream (". /jdbc. properties "); prop. load (in); driver = prop. getProperty ("jdbc. driver "); url = prop. getProperty ("jdbc. url "); user = prop. getPr Operty ("jdbc. user "); password = prop. getProperty ("jdbc. password ");} catch (IOException e) {e. printStackTrace () ;}}/*** get the Connection object * @ return */public static Connection getConnection () {Connection conn = null; try {Class. forName (driver); conn = DriverManager. getConnection (url, user, password);} catch (Exception e) {throw new RuntimeException (e);} return conn ;} /***** close the resource * @ param conn * @ para M pstmt * @ param stmt * @ param rs */public static void close (Connection conn, PreparedStatement pstmt, Statement stmt, ResultSet rs) {try {if (conn! = Null) {conn. close ();} if (pstmt! = Null) {pstmt. close ();} if (stmt! = Null) {stmt. close () ;}if (rs! = Null) {rs. close () ;}} catch (SQLException e) {throw new RuntimeException (e );}}

First, we can obtain information about all provinces when loading the page. The SQL statement is as follows:

Connection conn = null;  PreparedStatement pstmt = null;  Province province2 = null;    @Override  public ArrayList<Province> findAllPro() {   ResultSet rs = null;   ArrayList<Province> pros = null;   try {    String sql = "select id,place from province";    conn = ConnectionFactory.getConnection();    pstmt = conn.prepareStatement(sql);    pros = new ArrayList<Province>();        rs = pstmt.executeQuery();        while(rs.next()){     Province province = new Province();     province.setId(rs.getInt(1));     province.setPlace(rs.getString(2));     pros.add(province);    }       } catch (SQLException e) {    throw new RuntimeException(e);   }      return pros;  } 

Place the Retrieved Data in the background and create a SelectedServlet class to receive information from all provinces queried.

Response. setContentType ("app/json; charset = UTF-8"); response. setCharacterEncoding ("UTF-8"); request. setCharacterEncoding ("UTF-8"); // create a Place object ArrayList <Province> pros = new Place (). findAllPro (); PrintWriter out = response. getWriter (); // converts a set to a Json object out. write (JSONArray. fromObject (pros ). toString ());

Here we will use the set to convert the Json object. We need to import the following packages

Then we start to write the front-end page:

<Body> province: <select id = "province"> <option> -- select a province. </option> </select> city: <select id = "city"> <option> -- select a city -- </option> </select> <br/> <span> </span> </body>

Then, the jQuery code is as follows: (because the jQuery version I imported is relatively low, the method used is getJSON instead of getJson)

$.getJSON("SelectedServlet",function(data,textStatus){  var provinces = data;        var res = "";  for(var i =0;i<provinces.length;i++){  <span style="white-space:pre"> </span>res += "<option>"+provinces[i].place+"</option>";  }   $("#province").append(res);  }); 

In this way, data can be obtained during page loading.

Then let's start the interaction. First, add a change event to the drop-down box, obtain the selected information, and send the selected information to another CityServlet.

// Event triggered when the drop-down box is changed $ ("# province "). change (function () {var seled = $ ("option: selected" ).html (); $ ("span" ).html (seled); $. getJSON ("CityServlet", {"province": encodeURI (seled)}, function (data) {$ ("# city" ).html (""); var citys = data; var res = ""; for (var I = 0; I <citys. length; I ++) {res + = "<option>" + citys [I]. place + "</option>" ;}$ ("# city "). append (res );});});

The server queries the information obtained through SQL statements. The SQL code is as follows:

Public ArrayList <City> findAllCityByPro (String name) {ResultSet rs = null; ArrayList <City> citys = null; try {// obtain all values by name String SQL = "select c. city_place from city c, "+" province p where c. province_id = "+" (select id from province where place = '"+ name +"') "+" and c. province_id = p. id "; conn = ConnectionFactory. getConnection (); pstmt = conn. prepareStatement (SQL); citys = new ArrayList <City> (); System. out. println (SQL); rs = pstmt.exe cuteQuery (); while (rs. next () {City city = new City (); city. setPlace (rs. getString (1); citys. add (city);} System. out. println (citys);} catch (SQLException e) {e. printStackTrace ();} return citys ;}

Send the queried data to the background. After receiving the data, the background converts the data to a Json object and sends the data to the foreground through the callback function. Then, the foreground can directly obtain the data through the event, instead of redirecting pages, This Is Ajax (Asynchronous Javascript And XML ),

Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("app/json; charset = UTF-8"); response. setCharacterEncoding ("UTF-8"); request. setCharacterEncoding ("UTF-8"); // String proName = "Zhejiang"; String proName = URLDecoder. decode (URLDecoder. decode (request. getParameter ("province"), "UTF-8"), "UTF-8"); ArrayList <City> citys = new Place (). findAllCityByPro (proName); PrintWriter out = response. getWriter (); out. write (JSONArray. fromObject (citys ). toString ());}

The code for displaying the page is also written to the jQuery statement.

The effect is as follows:

The above example of using Ajax and Jquery to work with the database to implement the second-level linkage in the drop-down box is all the content shared by Alibaba Cloud. I hope you can give us a reference and support more.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.