Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid hard-coding the application context path in js/ajax scripts

I use Spring MVC and Javascript/ajax. I have an issue with the way my ajax scripts refer to a server-side resource.

Say I have two pages that need to use the same server-side resource through ajax:

The url for the first page is:

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

Say the server-side resource that my ajax script need to use is:

  • /myapp/geolocation/addressAutocomplete

As of now, I have hard-coded the application context path i.e. /myapp in my ajax script.

If and when my application context path changes I need to update is all over my scripts.

Is there a solution to that?

like image 546
balteo Avatar asked Sep 05 '13 15:09

balteo


People also ask

What is context in Ajax?

All the context does is it sets the value of this in the callbacks. So if you're in an event handler, and you want this in the callbacks to be the element that received the event, you'd do: context:this, success:function() { // "this" is whatever the value was where this ajax call was made }

What is context path in JavaScript?

The context path is the prefix of a URL path that is used to select the context(s) to which an incoming request is passed. Context path is also known as sub-path or sub-directory. Many apps are hosted at something other than the root (/) of their domain.

What is Ajax method in JavaScript?

AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.


2 Answers

In the HTML page that includes the script you could put an HTML base tag that points to the context. See the answer to How to get domain URL and application name?

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

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

like image 51
digitaljoel Avatar answered Sep 30 '22 18:09

digitaljoel


You can use $.ajaxPrefilter() to prepend context path to all jQuery AJAX requests.

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

like image 41
axtavt Avatar answered Sep 30 '22 16:09

axtavt