0

In my jsp I use <%String base = (String)application.getAttribute("base");%>

I tried to use 'base' in javascript but not work. Below is my javascript:

<script>
    var newBase = <%=base%>;
</script>

Can anyone help me to solve this?Thanks

4
  • what do you mean by not working? Commented Apr 22, 2014 at 8:34
  • if I use 'newBase', I can get the 'base' value Commented Apr 22, 2014 at 8:38
  • Have you tried printing this <%String base = (String)application.getAttribute("base");%>Does base is not null? Commented Apr 22, 2014 at 8:41
  • I already tried and it not null. Any idea? Commented Apr 22, 2014 at 8:44

2 Answers 2

1

This is the eplanation www.w3schools.com give for location object property pathname:
pathname: Sets or returns the path name of a URL
In our case the javascript file wich is in your context.

The first element is that pathname is the context So you split the attribute (see the split method in javascript String) and return it. This should do.

<script language='javascript'>
    function servletContext() {
        var sc = window.location.pathname.split( '/' );
        return "/"+sc[1];
    }   
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for posting an answer to this question! Code-only answers are discouraged on Stack Overflow, because a code dump with no context doesn't explain how or why the solution will work, making it difficult for the original poster (or any future readers) to understand the logic behind it. Please, edit your question and include an explanation of your code so that others can benefit from your answer. Thanks!
0

You can rather try it out like this ,

set the value to the hidden field ,

input type="hidden" id="hidVal" name="txt2" value="${base}"/>

And in your java script ,

<script>
var x = document.getElementById('hidVal').value;
alert(x);
</script>

Update :

var newBase = '<%=base%>';

You are missing the quotes to treat the value as string .

Hope this helps !!

3 Comments

Welcome :) Comment here if you face any issues with it
both method work but I prefer second method. Thanks san krish.:)
Happy to help :) . first one might be useful while validating forms

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.