简体   繁体   中英

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.

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>

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); .

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;

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM