6

私は単純な ajax 呼び出しをしようとしています。私が何をしても、常にエラーブロックが実行されます。doPost にヒットしない sysout があります。誰かが私が間違っていることを教えてください。これが私のコードです。

ジャバスクリプト----

$.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>
4

2 に答える 2

5

クライアントの URL は何ですか? URL は相対的になります。つまり、ページの URL が の<server>/foo/bar.html場合、ajax リクエストは に移動し<server>/foo/GetBulletAjaxます。しかし、サーブレットの定義は<server>/GetBulletAjax.

urlajax リクエストを に変更します/GetBulletAjax。リソースがサイトのルートから離れていることをブラウザーに伝えるには、先頭のスラッシュが必要です。

于 2013-04-29T01:18:15.700 に答える
2

Jquery ドキュメントで

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

type (デフォルト: 'GET') タイプ: 文字列 作成するリクエストのタイプ ("POST" または "GET")。デフォルトは "GET" です。注: PUT や DELETE などの他の HTTP 要求メソッドもここで使用できますが、すべてのブラウザーでサポートされているわけではありません。

POST である必要がある type 属性を見逃しているようです。ドキュメントに記載されているように、デフォルトはGETです。それをサポートするために、サーブレットにdoGetがありません。

$.ajax({
   url: "GetBulletAjax",
   dataType: 'json',
   type:POST,
   success: function(data) {
      alert("success");
   },
   error: function(jqXHR, textStatus, errorThrown) {
      alert(jqXHR+" - "+textStatus+" - "+errorThrown);
   }       
}); 
于 2013-04-29T00:44:10.023 に答える