Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform equivalent of JSTL's c:url in JavaScript?

I have some JavaScript that is making an Ajax call to a relative url (using jQuery).

var servletUrl = "someservlet";

$.ajax({
    type: "POST",
    url: servletUrl,
    success: function(response) {
        // ...
    }
});

Where "someservlet" is:

@WebServlet("/someservlet")
public class SomeServlet extends HttpServlet

I use this same script in multiple pages. When used from a page that is in the servlet context root, then the relative url resolves relative to the servlet context root, which is correct. When used from a page that is in a subfolder the URL resolves relative to the subfolder, which will return 404 error.

I would like to be able to reuse this JavaScript without having to modify it depending on the type of page that it is used within. Ideally, I need the equivalent of the JSTL's <c:url> tag. Is there anything in JavaScript that allows me to create URLs relative to the servlet context root?

like image 236
KevinS Avatar asked Oct 06 '11 22:10

KevinS


1 Answers

Several options:

  1. Set a HTML <base> element with that value (note: has its own advantages and disadvantages)

    <head>
        <base href="${pageContext.request.contextPath}/" />
        ...
    </head>
    

    and then in JS:

    var contextPath = $("base").attr("href");
    var servletUrl = contextPath + "someservlet";
    // ...
    

  2. Or set a data attribute somewhere

    <html data-contextPath="${pageContext.request.contextPath}/">
        ...
    </html>
    

    and then in JS:

    var contextPath = $("html").data("contextPath");
    var servletUrl = contextPath + "someservlet";
    // ...
    

  3. Or set a global JS variable with that value (poor practice):

    <head>
        ...
        <script>var contextPath = "${pageContext.request.contextPath}/";</script>
    </head>
    

    and then in JS:

    var servletUrl = contextPath + "someservlet";
    // ...
    
like image 81
BalusC Avatar answered Sep 28 '22 09:09

BalusC