ajax查询数据库,服务器传回json字符串,js解析json

前端之家收集整理的这篇文章主要介绍了ajax查询数据库,服务器传回json字符串,js解析json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

服务器端获得要查询的东西,查询数据库,将查询的信息,以json字符串的形式返回给浏览器

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();
        }

    }

js解析json,获得返回的内容

function updateSpeciality(str) {
            var xmlhttp;
            if (str=="")
            {
                alert("请选择非空的值!");
                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+")");//转换为json对象

                    for(var o in dataObj.specialities)
                    {
                        alert(dataObj.specialities[o].specialityID);
                        alert(dataObj.specialities[o].SPname);

                    }


                }
            }
            xmlhttp.open("GET","/First/servlet/GetMessage?departmentID="+str,true);
            xmlhttp.send();

        }
原文链接:https://www.f2er.com/ajax/163057.html

猜你在找的Ajax相关文章