Question

I know this question are asked hundreds of times :( but I just want to learn more :).

My question is simple, can I pass a value to a js file like this, if not, how ?

<script type="text/javascript" src="./js/create.js?method=create"></script>

Yes, you notice that I have a parameter method=create which I want to use in my create.js.

I know in jquery ajax, we have an easy way, but you must notice that the ajax method is in included in the js file, how could I pass a parameter to the js file itself ?

Any answer is welcome :) Thanks.

Was it helpful?

Solution 2

Not really, no. What you can do is this:

<script type="text/javascript">
  var method = "create";
</script>
<script type="text/javascript" src="./js/create.js"></script>

Another way is to only define functions inside your javascript file, and then invoke after it has loaded.

<script type="text/javascript" src="./js/create.js"></script>
<script type="text/javascript">
  runMyLoadedCode("create");
</script>

Third way is belying my first simplistic answer: access the script tag itself and parse it. You can see here how to access the tag that has loaded your script; take its src value and cut it up to locate your method=create.

OTHER TIPS

This works perfect for me:

<script src="js/script.js" id="myScript" data-url="my_variable"></script>

inside the script.js file:

var myUrl = document.getElementById("myScript").getAttribute( "data-url" );

"myUrl = my_variable" inside the code

you can use myUrl everywhere.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top