繁体   English   中英

Jquery ajax调用没有命中servlet

[英]Jquery ajax call is not hitting servlet

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

JavaScript的----

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

Java的----

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>

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

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

在Jquery文档中

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

type(默认值:'GET')类型:String要生成的请求类型(“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);
   }       
}); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM