How to call servlet from jQuery $.ajax without get

2020-02-06 16:51发布

问题:

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

$.ajax({
  url: 'CheckingAjax',
  type: 'GET',
  data: { field1: "hello", field2 : "hello2"} ,
  contentType: 'application/json; charset=utf-8',
  success: function (response) {
    //your success code
    alert("success");
  },
  error: function (errorThrown) {
    //your error code
    alert("not success :"+errorThrown);
  }                         
});

However, it goes to error function and shows alert:

not success :Not Found

How is this caused and how can I solve it?

回答1:

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"