Ajax queries the database, the server returns a json string, js parses json, and ajaxjson
The server obtains the information to be queried, queries the database, and returns the information to the browser in the form of a json string.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String departmentID=request.getParameter("departmentID"); DataBaseHandle dataBaseHandle=new DataBaseHandle("commonUser", "common", "jdbc:mysql://127.0.0.1:3306/firstwebsite"); String SQL="select * from speciality where departmentID='"+departmentID+"'"; String json="{'specialities':["; response.setContentType("text/html; charset=utf-8"); response.setCharacterEncoding("UTF-8"); try { ResultSet rs=dataBaseHandle.exeuteSQL(SQL); while(rs.next()) { json=json+"{'"+"specialityID':'"+rs.getString(1)+"',"+"'SPname':'"+rs.getString(2)+"'},"; System.out.println(rs.getString(1)+rs.getString(2)); } json=json.substring(0,json.length()-1); json=json+"]}"; PrintWriter pwriter=response.getWriter(); pwriter.print(json); rs.close(); dataBaseHandle.closeResourse(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
Parse json in js to get the returned content
Function updateSpeciality (str) {var xmlhttp; if (str = "") {alert ("Please select a non-empty value! "); Return;} if (window. XMLHttpRequest) {// code for IE7 +, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest ();} else {// code for IE6, IE5 xmlhttp = new ActiveXObject ("Microsoft. XMLHTTP ");} xmlhttp. onreadystatechange = function () {if (xmlhttp. readyState = 4 & xmlhttp. status = 200) {var dataObj = eval ("(" + xmlhttp. responseText + ")"); // converts to a json object for (var o in dataObj. specialities) {alert (dataObj. Specialities [o]. specialityID); alert (dataObj. specialities [o]. SPname) ;}} xmlhttp. open ("GET", "/First/servlet/GetMessage? Repeated mentid = "+ str, true); xmlhttp. send ();}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.