Jquery ajax调用没有命中servlet

时间:2013-04-29 00:13:28

标签: java javascript jquery ajax

我正在尝试进行简单的ajax调用。无论我做什么,它总是执行错误块。我在doPost中有一个从未被击中的sysout。有人请告诉我我做错了什么。这是我的代码。

的javascript ----

$.ajax({
    url: "GetBulletAjax",
    dataType: 'json',
    success: function(data) {
        alert("success");
    },
     error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR+" - "+textStatus+" - "+errorThrown);
    }       
}); 

爪哇----

public class GetBulletAjax extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public GetBulletAjax() {
        super();
    }

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("made it to servlet");
        PrintWriter out = response.getWriter(); 
        User user = (User) request.getSession().getAttribute("user");
        int userId = user.getId();
        List<Bullet> bullets;

        BulletDAO bulletdao = new BulletDAOImpl();
        try {
            bullets = bulletdao.findBulletsByUser(userId);
            Gson gson = new Gson();
            String json = gson.toJson(bullets);
            System.out.println(json);
            out.println(json);
            out.close();

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }

}

的web.xml ----

<servlet>
    <servlet-name>GetBulletAjax</servlet-name>
    <servlet-class>bulletAjax.GetBulletAjax</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GetBulletAjax</servlet-name>
    <url-pattern>/GetBulletAjax</url-pattern>
</servlet-mapping>

2 个答案:

答案 0 :(得分:4)

您客户的网址是什么?您的网址将是相对的 - 因此,如果您网页的网址为<server>/foo/bar.html,则您的ajax请求将转到<server>/foo/GetBulletAjax。但是您的servlet定义是<server>/GetBulletAjax

将您的ajax请求中的url更改为/GetBulletAjax。您需要使用前导斜杠来告诉浏览器资源位于站点根目录之外。

答案 1 :(得分:1)

在Jquery文档中

http://api.jquery.com/jQuery.ajax/

类型(默认:'GET') 类型:字符串 要求的类型(“POST”或“GET”),默认为“GET”。注意:此处也可以使用其他HTTP请求方法,例如PUT和DELETE,但并非所有浏览器都支持它们。

似乎你错过了需要POST的type属性。默认是文档中提到的GET。你的servlet中没有doGet来支持它。

$.ajax({
   url: "GetBulletAjax",
   dataType: 'json',
   type:POST,
   success: function(data) {
      alert("success");
   },
   error: function(jqXHR, textStatus, errorThrown) {
      alert(jqXHR+" - "+textStatus+" - "+errorThrown);
   }       
}); 
相关问题