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
In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting.
JavaScript is always pass-by-value. This means everything in JavaScript is a value type and function arguments are always passed by value. That being said, object types are a bit more confusing. The confusion lies in the fact that object types are reference types which are passed by value.
Javascript pass by value:In javascript pass by value, the function is called by directly passing the value of the variable as the argument. Therefore, even changing the argument inside the function doesn't affect the variable passed from outside the function.
In JavaScript, object references are values. Because of this, objects will behave like they are passed by reference: If a function changes an object property, it changes the original value. Changes to object properties are visible (reflected) outside the function.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With