当ajax调用servlet

时间:2015-07-26 16:16:45

标签: javascript ajax json jsp servlets

我正在尝试制作依赖下拉列表。为此,我创建了一个jsp页面,并通过ajax调用调用servlet。在servlet中,我使用Json对象返回下拉列表的值。值正确地出现在Json对象中但是请求已经完成并出现了一些错误(因为调用了成功方法而不是调用错误方法)。

这是我的ajax代码:

$.ajax({ type: "GET",   
             url: "MyServlet?index="+listindex, 
             datatype: 'JSON', 
              error : function() {

            alert("Error");
              },
            success : function(data) {
       try{
        var citiArray=JSON.parse(data);

        if(citiArray != null){

        for(var s=0;s<citiArray.length;s++){

        var serial=citiArray[s];
        //populating drop down list
           $("#dname").append($("<option></option>").val(serial.authors1).html(serial.authors1));
        }
        }
        }
             catch(err){
             alert(err);
                 }
            }
     });

My Servlet code :MyServlet.java

 public class MyServlet extends HttpServlet {
   /**
 * @see HttpServlet#HttpServlet()
 */
public MyServlet() 
{
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

   try { 

    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con =DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/orcl" ,"hr", "password");

     request.setCharacterEncoding("utf8");
    response.setCharacterEncoding("utf8");
    response.setContentType("application/json"); 
    PrintWriter out = response.getWriter(); 

    String listindex = request.getParameter("index");
    out.print(listindex);
  String query2 = "select module from course where cname=?";
 PreparedStatement st2 = con.prepareStatement(query2);
 st2.setString(1,listindex);
 ResultSet rs2=st2.executeQuery();

  JSONArray uniList1 = new JSONArray();
  while (rs2.next()) 
   {
       uniList1.add(rs2.getString("module"));
       //System.out.println(rs2.getString("module"));
    }


    JSONObject obj = new JSONObject();
    obj.put("key", uniList1 );
    System.out.println(obj);
    out.print(obj);
  }
   catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
    }
}

web.xml:

  <servlet-name>MyServlet</servlet-name>  
  <servlet-class>com.dac.MyServlet</servlet-class>  
  </servlet>  

  <servlet-mapping>  
  <servlet-name>MyServlet</servlet-name>  
  <url-pattern>/MyServlet</url-pattern>  
  </servlet-mapping>  

由于 罗希特夏尔

1 个答案:

答案 0 :(得分:1)

即使抛出异常也会发送回复

 catch (Exception e) 
{
    // TODO Auto-generated catch block
    e.printStackTrace();
    //send the response
    out.print(e.getMessage());
}

您可以通过以下方式获得错误的详细说明:

 error: function (theRequest, theStatus, theError) 
 {
    alert(theRequest.responseText);
}

而不是

  error : function() {

        alert("Error");
          }