0

I am creating a webapp and I have been using tag in my JSPs to ensure that all my links (both to pages and to resources such as images/css) are always consistent from the root of the application, and not relative to my current location.

Some of the content I am creating using jQuery, for example, I am creating a HTML table by parsing a JSON object and using jquery.append() to insert it in to a div.

My question is, if I want to dynamically create a link using jquery how can I achieve a consistent URL regardless of the page being executed? I have tried just building the html with the tag in it, but no joy.

Thanks!

2 Answers 2

1
var baseURL = "/* Server-side JSP code that sets the base URL */";

$("<a />", { href: baseURL+"/my/resource/here.jsp" }); //Your proper link

Or you could do:

var baseURL = "http://"+location.host+"/my/base/url/";
//Which gives you something like http://mySite.com/my/base/url/
Sign up to request clarification or add additional context in comments.

Comments

1

Get the root value of your webapp into a string using a jsp tag inside your javascript.

 var root = < %=myRootVariable%> //This evaluates to http://www.myapp.com
    var dynamicBit = "/foo/bar"
    var dynamicLinkUrl = root + dynamicBit
    var $newa = $("<a href='" + dynamicLinkUrl +'">Hello, world</a>");
    $someJQElement.append($newa)

Hopefully none of this will occur in the global namespace. Just sayin'

1 Comment

And there needs to be quotes around that root variable.

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.