2

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.

Romeo
  • 376
  • 1
  • 3
  • 14
diligent
  • 2,282
  • 8
  • 49
  • 64
  • See this: http://stackoverflow.com/questions/2190801/passing-parameters-to-javascript-files – Romeo Jun 27 '13 at 01:34

2 Answers2

8

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.

Alp Altunel
  • 3,324
  • 1
  • 26
  • 27
3

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.

Community
  • 1
  • 1
Amadan
  • 191,408
  • 23
  • 240
  • 301