ajax调用提供重复和意外的输出

时间:2015-03-27 12:27:42

标签: jquery ajax servlets

这是我的ajax电话:                                          

           <script type="text/javascript">
            var dataString ={ "EmployeeNum" : 50};
            var queryObject="";
            var queryObjectLen="";
            console.log("loading");
            google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(RequestData);

create function RequestData() 
{
    $.ajax
    (
    {
        type : 'POST',
        asynch :'false',
        data:  dataString,
        url : 'http://localhost:8080/Charts/db',
        success : function(data) 
        {
        alert("success");
            queryObject = jQuery.parseJSON(data);            
            queryObjectLen = queryObject.Details.length;
            console.log("queryObj: "+queryObject+" Length: "+queryObjectLen);
            drawChart();
        },
        error : function(xhr, type)
         {

            alert('server error occoured')
          }
    })
);

            function drawChart()
            {

                console.log("Inside drawChart()");
                var arrdata = new google.visualization.DataTable();
                arrdata.addColumn('string', 'DeptName');
                arrdata.addColumn('number', 'NumberOfEmployees');

                for(var i=0; i<queryObjectLen; i++)
                {
                    console.log(queryObject.Details[i].DeptName);
                    var dept= queryObject.Details[i].DeptName;

                    var emp = queryObject.Details[i].NumberOfEmployees;

                     arrdata.addRows([
                        [dept,parseInt(emp)]
                    ]);
                }   
                 var options = {
                    title: 'Department vs. Number of Employees on Horizontal Axis',
                    vAxis: {title: 'DeptName',  titleTextStyle: {color: 'red'}},
                    'width':400,
                    'height':300
                };
                var option2 = {
                title: 'Department vs. Number of Employees on vertical Axis',
                hAxis: {title: 'NumberOfEmployees',  titleTextStyle: {color: 'blue'}},
                'width':400,
                'height':300
                };

                var option3 = {
                title: 'Department vs. Number of Employees on Pie Chart',
                'width':400,
                'height':300
                };
                var option4 = {
                title: 'Department vs. Number of Employees on Line Chart',
                'width':400,
                'height':300
                };
           var chart = new google.visualization.BarChart(document.getElementById('chart_div'));//this is altogether a different object
           var chart2 = new google.visualization.ColumnChart(document.getElementById('chart_div2'));
            var chart3 = new google.visualization.PieChart(document.getElementById('chart_div3'));
           var chart4 = new google.visualization.LineChart(document.getElementById('chart_div4'));
            chart.draw(arrdata, options);
            chart2.draw(arrdata, option2);
            chart3.draw(arrdata, option3);
            chart4.draw(arrdata, option4);
        }

    </script>
  </head>

  <body>
    <div id="chart_div" style="width: 400px; height: 300px;"></div>
    <div id="chart_div2" style="width: 800px; height: 400px;"></div>
    <div id="chart_div3" style="width: 400px; height: 300px;"></div>
    <div id="chart_div4" style="width: 400px; height: 500px;"></div>


  </body>
</html>

它转到url http://localhost:8080/Charts/db的servlet,并根据传递给它的参数,执行查询。

问题:我的输出和流量控制完全出乎意料。

以下是我在输出中的内容:

enter image description here servlet的doGet函数如下所示:

问题:

1.为什么我打印了两次查询?

  1. 为什么我有两次警报?

  2. 异常会在最外面的块中捕获,然后如何打印查询?

  3. 这是我的功能:

    public  void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        try
        {
            List<JSONObject> Details = new LinkedList<JSONObject>();
            PrintWriter out = response.getWriter();
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            c = DriverManager.getConnection(dbURL, user, password);
            query = "select DeptName, NumberOfEmployees from Departments where 1 = 1";
            String Dept = "";
            String EmployeeNum= "";
            try
            {
                EmployeeNum = request.getParameter("EmployeeNum");
            }
            catch(Exception e)
            {
                System.out.println("error in get param" + e );
            }
            int NumOfEmp;
            try {
                NumOfEmp = Integer.parseInt(EmployeeNum);
            } catch(NumberFormatException e){
                StringBuilder sb = new StringBuilder();
                sb.append("Error parsing this EployeeNum: ");
                sb.append(EmployeeNum);
                e.printStackTrace();
                throw new RuntimeException(sb.toString());
            }
    
            if (NumOfEmp > 0) {
                // add criteria for Age
                query += " AND NumberOfEmployees = "+ NumOfEmp ;  
            }
            System.out.println("QUERY ......... " +  query);
            pst = c.prepareStatement(query);
            rs = pst.executeQuery();
            resobj = new JSONObject();
            while(rs.next())
            {
                String DeptName = rs.getString(1);
                System.out.println("name " + DeptName);
                int NumberOfEmployees = rs.getInt(2);
                System.out.println("num " + NumberOfEmployees );
                obj = new JSONObject();
                obj.put("DeptName", DeptName);
                obj.put( "NumberOfEmployees",NumberOfEmployees );
                Details.add(obj);
            }
            resobj.put("Details", Details);
            out.write(resobj.toString());  
        }
        catch(Exception e)
        {
            System.out.println("Exception aayi: " + e);
        }
    }
    

    编辑以回答:

    2015-03-27T21:35:46.964+0530|INFO: QUERY ......... select DeptName, NumberOfEmployees from Departments where 1 = 1 AND NumberOfEmployees = 50
    2015-03-27T21:35:47.685+0530|SEVERE: SLF4J: The requested version 1.6 by your slf4j binding is not compatible with [1.5.5, 1.5.6]
    2015-03-27T21:35:47.685+0530|SEVERE: SLF4J: See http://www.slf4j.org/codes.html#version_mismatch for further details.
    2015-03-27T21:36:00.325+0530|INFO: Exception aayi: java.lang.RuntimeException: Error parsing this EployeeNum: null
    2015-03-27T21:36:00.325+0530|SEVERE: java.lang.NumberFormatException: null
    

2 个答案:

答案 0 :(得分:0)

  1. 可能是你的setOnLoadCallback被叫了两次。
  2. 见1
  3. 您的代码不会抛出异常,因此会调用以下语句:
    System.out.println("QUERY ......... " + query);

答案 1 :(得分:0)

SERVLET

    public  void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    try
    {
        List<JSONObject> Details = new LinkedList<JSONObject>();
        PrintWriter out = response.getWriter();
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        c = DriverManager.getConnection(dbURL, user, password);
        query = "select DeptName, NumberOfEmployees from Departments where 1 = 1";
        String Dept = "";
        int EmployeeNum = 0;
        try
        {
            EmployeeNum = request.getParameter("EmployeeNum");
        }
        catch(Exception e)
        {
            System.out.println("error in get param" + e );
        }
        int NumOfEmp;
        try {
            NumOfEmp = EmployeeNum;
        } catch(NumberFormatException e){
            StringBuilder sb = new StringBuilder();
            sb.append("Error parsing this EployeeNum: ");
            sb.append(EmployeeNum);
            e.printStackTrace();
            throw new RuntimeException(sb.toString());
        }

        if (NumOfEmp > 0) {
            // add criteria for Age
            query += " AND NumberOfEmployees = "+ NumOfEmp ;  
        }
        System.out.println("QUERY ......... " +  query);
        pst = c.prepareStatement(query);
        rs = pst.executeQuery();
        resobj = new JSONObject();
        while(rs.next())
        {
            String DeptName = rs.getString(1);
            System.out.println("name " + DeptName);
            int NumberOfEmployees = rs.getInt(2);
            System.out.println("num " + NumberOfEmployees );
            obj = new JSONObject();
            obj.put("DeptName", DeptName);
            obj.put( "NumberOfEmployees",NumberOfEmployees );
            Details.add(obj);
        }
        resobj.put("Details", Details);
        out.write(resobj.toString());  
    }
    catch(Exception e)
    {
        System.out.println("Exception aayi: " + e);
    }
}

JS

script type="text/javascript">

        var dataString ={ "EmployeeNum" : 50};
        var queryObject="";
        var queryObjectLen="";
        console.log("loading");
        google.load('visualization', '1.0', {'packages':['corechart']});
        google.setOnLoadCallback(RequestData);

        function RequestData(){
            $.ajax({
                type : 'POST',
                asynch :'false',
                data:  dataString,
                url : 'http://localhost:8080/Charts/db',
                success : function(data) 
                {
                alert("success");
                    queryObject = jQuery.parseJSON(data);            
                    queryObjectLen = queryObject.Details.length;
                    console.log("queryObj: "+queryObject+" Length: "+queryObjectLen);
                    drawChart();
                },
                error : function(xhr, type)
                 {

                    alert('server error occoured')
                  }
            })
        }

        function drawChart(){

            console.log("Inside drawChart()");
            var arrdata = new google.visualization.DataTable();
            arrdata.addColumn('string', 'DeptName');
            arrdata.addColumn('number', 'NumberOfEmployees');

            for(var i=0; i<queryObjectLen; i++)
            {
                console.log(queryObject.Details[i].DeptName);
                var dept= queryObject.Details[i].DeptName;

                var emp = queryObject.Details[i].NumberOfEmployees;

                 arrdata.addRows([
                    [dept,parseInt(emp)]
                ]);
            }   
             var options = {
                title: 'Department vs. Number of Employees on Horizontal Axis',
                vAxis: {title: 'DeptName',  titleTextStyle: {color: 'red'}},
                'width':400,
                'height':300
            };
            var option2 = {
            title: 'Department vs. Number of Employees on vertical Axis',
            hAxis: {title: 'NumberOfEmployees',  titleTextStyle: {color: 'blue'}},
            'width':400,
            'height':300
            };

            var option3 = {
            title: 'Department vs. Number of Employees on Pie Chart',
            'width':400,
            'height':300
            };
            var option4 = {
            title: 'Department vs. Number of Employees on Line Chart',
            'width':400,
            'height':300
            };

        var chart = new google.visualization.BarChart(document.getElementById('chart_div'));//this is altogether a different object
        var chart2 = new google.visualization.ColumnChart(document.getElementById('chart_div2'));
        var chart3 = new google.visualization.PieChart(document.getElementById('chart_div3'));
        var chart4 = new google.visualization.LineChart(document.getElementById('chart_div4'));
        chart.draw(arrdata, options);
        chart2.draw(arrdata, option2);
        chart3.draw(arrdata, option3);
        chart4.draw(arrdata, option4);
    }

        </script>
      </head>

      <body>
        <div id="chart_div" style="width: 400px; height: 300px;"></div>
        <div id="chart_div2" style="width: 800px; height: 400px;"></div>
        <div id="chart_div3" style="width: 400px; height: 300px;"></div>
        <div id="chart_div4" style="width: 400px; height: 500px;"></div>


      </body>
    </html>