0

I wish to pass a request parameter to the JavaScript that is to be loaded. This parameter can then be used as a constant within the script.

One example of this is how fancybox 2.x requres a v=2.1.0 parameter as defined in the instructions.

Searching through the fancybox source I could not identify how this gets used, it's required for both the CSS and JavaScript.

My main requirement for this is to be able to pass in an application context path to the JS which handles ReST requests.

<script type="text/javascript"
        src="<c:url value="/js/rest.js?ctx=${pageContext.request['contextPath']}"/>"></script>
1
  • Where is it written that it's required? I see just an example. Commented Aug 31, 2012 at 7:43

3 Answers 3

3

First you have to identify the script (you can give a script tag an id). Scripts are in the document.scripts nodelist. Then you take the src attribute of it (a string), split it on the question mark and take the second element of the resulting array. That can be processed further.

Something like:

var script = document.scripts[0]
   ,params = script.src.split('?')[1].split('&')
   ,paramsObj = {};

for (var i=0;i<params.length;i+=1){
  var keyvalue = params[i].split('=');
  paramsObj[keyvalue[0]] = keyvalue[1];
}
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure exactly what you're trying to achieve.

If you want JavaScript to be able to read a value from the query string of the URL of the current page you can just do:

// URL of current document is http://example.com/mypage.html?ctx=thingy
location.search.ctx; // thingy

But if you want to pass a parameter from the markup through to the JavaScript file why don't you just set it in the document beforehand?

<script>
    ctx = ${pageContext.request['contextPath']};
</script>

<script src="/js/rest.js"></script> // rest.js just references ctx directly.

Comments

0

If you can use jQuery, you can first select all scripts where the src attribute starts with /js/rest.js, then get the parameter in the src attribute.

function getCtx(){    
  $("script[src^='/js/rest.js']").each(function(){
    return this.src.replace("/js/rest.js?ctx=", "");
  });
}

In other cases you might need to use decodeURIComponent on it.

Comments

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.