How to call servlet from jQuery $.ajax without getting HTTP 404 error

前端 未结 1 472
-上瘾入骨i
-上瘾入骨i 2020-12-11 08:58

I am trying to call a servlet using ajax call as below:

$.ajax({
  url: \'CheckingAjax\',
  type: \'GET\',
  data: { field1: \"hello\", field2 : \"hello2\"}          


        
相关标签:
1条回答
  • 2020-12-11 09:48

    When you specify a relative URL (an URL not starting with scheme or /), then it will become relative to the current request URL (the URL you see in browser's address bar).

    You told that your servlet is available at:

    http://localhost:8080/FullcalendarProject/CheckingAjax

    Imagine that the web page where your ajax script runs is opened via:

    http://localhost:8080/FullcalendarProject/pages/some.jsp

    And you specify the relative URL url: "CheckingAjax", then it will be interpreted as:

    http://localhost:8080/FullcalendarProject/pages/CheckingAjax

    But this does not exist. It will thus return a HTTP 404 "Page Not Found" error.

    In order to get it to work, you basically need to specify the URL using one of below ways:

    1. url: "http://localhost:8080/FullcalendarProject/CheckingAjax"

      This is not portable. You'd need to edit it everytime you move the webapp to another domain. You can't control this from inside the webapp.

    2. url: "/FullcalendarProject/CheckingAjax"

      This is also not really portable. You'd need to edit it everytime you change the context path. You can't control this from inside the webapp.

    3. url: "../CheckingAjax"

      This is actually also not portable, although you can fully control this from inside the webapp. You'd need to edit it everytime you move around JSP into another folder, but if you're moving around JSPs you're basically already busy coding, so this could easily be done at the same time.

    4. Best way would be to let JSP EL dynamically print the current request context path. Assuming that the JS code is enclosed in JSP file:

      url: "${pageContext.request.contextPath}/CheckingAjax"

      Or when it's enclosed in its own JS file (good practice!), then create either a global JS variable:

      <script>var contextPath = "${pageContext.request.contextPath}";</script>
      <script src="yourajax.js"></script>
      

      With

      url: contextPath + "/CheckingAjax"

      or a HTML5 data attribute on the document element:

      <html data-contextPath="${pageContext.request.contextPath}">
          <head>
              <script src="yourajax.js"></script>
      

      With

      url: $("html").data("contextPath") + "/CheckingAjax"

    0 讨论(0)
提交回复
热议问题