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?
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?
Share Improve this question asked Sep 5, 2013 at 15:04 balteobalteo 24.7k67 gold badges234 silver badges436 bronze badges3 Answers
Reset to default 7In 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?
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).
I had the same problem in a JSP page using an AJAX request within an external JS file, I solved the problem by using a hidden field in JSP containing the contextPath:
<input type="hidden" id="contextPath" value="<%=request.getContextPath()%>" readonly></input>
In JS file, get the value of the hidden field:
var contextPath = $('#contextPath').val();
Finally, make the request call by concatenating the context path and the relative url like:
$.ajax({
type: "GET",
contentType : "application/json",
dataType: 'json',
url: contextPath + '/home/reporting',
success: function(data) {
}
});
Hope this help anyone facing the same issue