19

I want to pass a parameter to some javascript using a single line of code, like this:

<script language="JavaScript" src="courselist.js?subj=MATH" type="text/javascript" />

Inside the javascript file, how can I get the value of the parameter "subj"?

Thanks

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
jeph perro
  • 6,242
  • 26
  • 90
  • 124

5 Answers5

18

That's as far only possible by accessing "own" <script> element in the HTML DOM and parse the src attribute.

Long story short, here's a nice article with detailed explanations and code samples: http://feather.elektrum.org/book/src.html

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
17

Why not just create the variable in inside a script tag before including the javascript file?

<script type="text/javascript">
    var subj = "MATH";
</script>
<script language="JavaScript" src="courselist.js" type="text/javascript"></script>
okalex
  • 788
  • 5
  • 12
  • This is how I have done it now, I was trying to keep the code to a single line. This line of code is going to be used to include some dynamic content through our CMS. – jeph perro Jun 30 '10 at 00:22
  • 2
    Well, if you REALLY want it on a single line, you could just remove the line breaks ;) – okalex Jun 30 '10 at 00:28
2

The only way to get something like this to work is to have the server serving up a dynamically generated javascript file where it has something like this on the server:

if(Parameters["subj"]=="MATH"){
  jsfile="var subj='MATH'; "+jsfile;
}...
Earlz
  • 62,085
  • 98
  • 303
  • 499
0

I don't think the Javascript file would be aware of the parameter that is passed to it. If that address goes to some sort of server-side script (NOT just a static Javascript file), then you may be able to do something with it.

Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
0

When a script, loaded from a script src file is interpreted, its related script element exists in the document.

Don't worry about which file is which- look at every script element for an url with a query string.

kennebec
  • 102,654
  • 32
  • 106
  • 127