Avoiding hard coding of application context path in js / ajax scripts

I am using Spring MVC and Javascript / ajax . I have a problem with how my ajax scripts reference a server resource.

Let's say I have two pages that should use the same server resource through ajax:

URL for the first page:

  • /myapp/advertisement/28/edit
  • /myapp/signup

Tell the server resource my ajax script should use:

  • /myapp/geolocation/addressAutocomplete

At the moment, I have a hard-coded path to the application context, i.e. /myapp in my ajax script.

If and when the path to the application context changes, I need to update all my scripts.

Is there a solution for this?

+6
source share
2 answers

On the HTML page containing the script, you can place the HTML base tag that points to the context. See Answer to How to get the domain URL and application name?

And you can read the base tag at http://www.w3schools.com/tags/tag_base.asp , which reads The <base> tag specifies the base URL/target for all relative URLs in a document.

Before deciding whether to use this tag, it might be worth reading the answers to Is the html <base> tag recommended?

+6
source

You can use $.ajaxPrefilter() to add the path to all jQuery AJAX requests.

It can be configured in the <script> element on your pages where the context path value is available (for example, ${pageContext.request.contextPath} in JSP).

+6
source

Source: https://habr.com/ru/post/953247/


All Articles