Server-side Get what to query, query the database, the query information, in the form of a JSON string returned to the browser
public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexceptio n {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(0Json. 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();} }
JS Parse json to get the content returned
function updatespeciality(str) { varxmlHTTPif(str=="") {alert ("Please select a value that is not empty!");return; }if(Window. XMLHttpRequest) {//code for ie7+, Firefox, Chrome, Opera, Safarixmlhttp=NewXMLHttpRequest (); }Else{//code for IE6, IE5xmlhttp=NewActiveXObject ("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange= function() { if(xmlhttp.readystate==4&& xmlhttp.status== $) {vardataobj=Eval("("+xmlhttp.responsetext+")");//Convert to JSON object for(varOinchdataobj.specialities) {alert (Dataobj.specialities[o].specialityid); Alert (dataobj.specialities[o). Spname); }}} Xmlhttp.open ("GET","/first/servlet/getmessage?departmentid="+STR,true); Xmlhttp.send (); }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Ajax query database, server returns JSON string, JS parsing json