greenbandit
greenbandit

Reputation: 2275

pass a variable from js to jquery

wondering how I can pass a variable from load js like:

<script type="text/javascript" src="script.js?myVar=myValue"></script>

and use and pass to script.js itself? I Know about declare variable before, but I'm looking for url way.

Thanks in advance.

Upvotes: 0

Views: 125

Answers (4)

Alex Wayne
Alex Wayne

Reputation: 187272

The javascript wont have access to that value. The server would have to look for that and insert that value into the rendered javascript on your behalf.

Usually though, the pattern is more like this:

<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
  ObjFromScript.myVar = 'myValue';
  ObjFromScript.doStuff();
</script>

Upvotes: 3

alex
alex

Reputation: 490657

You could use document.currentScript, but it isn't widely supported.

var matches = document.currentScript.src.match(/\?myVar=([^&]+)/),
    myVarParam = matches && matches[1];

Alternatively, you could try getting the script element with the matching URL and parse out the GET param.

var scriptPath = 'path/to/this/script.js',
    matches = $('script[src^="' + scriptPath + '"]').attr('src').match(/\?myVar=([^&]+)/),
    myVarParam = matches && matches[1];

Upvotes: 0

Anurag
Anurag

Reputation: 141909

You could do it on the client or the server. On the client, get hold of the script element and parse the src attribute.

<script id="myScript" src="script.js?myVar=foo"></script>
<script>
    var s = document.getElementById('myScript');
    s.src; // parse it and extract myVar
</script>

On the server, setup routes so that script.js goes to some handler written in a server-side language like PHP. In that case you could be outputting script.js dynamically. Here's an example in PHP.

script.js => script.php

<?php 
    header('Content-Type: application/javascript');
    $myVar = $_GET['myVar'];
?>

// optionally expose myVar inside JavaScript
var myVar = <?php json_encode($myVar) ?>;

// regular JavaScript
alert(myVar);
var x = 10;

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318808

You'd have to locate the <script> tag in the document and extract the arguments. A prominent example of a site using this is facebook with the #xfbml=1 hashtag.

However, the proper/nice way is not putting any code but functions in script.js and then call someFunction(myValue);.

Upvotes: 2

Related Questions