admin管理员组

文章数量:1295711

Pretty straightforward, I've got a JS script that's included on many different sites and needs to have parameters passed to it.

It would be useful if those could be passed via the URL, eg:

<script type="text/javascript" 
    src=".js?var1=something&var2=somethingelse"></script>

Yes, you can still pre-populate variables, in a separate script tag, but it's a smidge messy and less easy to pass around:

<script type="text/javascript">var1=something; var2=somethingelse</script>
<script type="text/javascript" src=".js"></script>

Pretty straightforward, I've got a JS script that's included on many different sites and needs to have parameters passed to it.

It would be useful if those could be passed via the URL, eg:

<script type="text/javascript" 
    src="http://path.to/script.js?var1=something&var2=somethingelse"></script>

Yes, you can still pre-populate variables, in a separate script tag, but it's a smidge messy and less easy to pass around:

<script type="text/javascript">var1=something; var2=somethingelse</script>
<script type="text/javascript" src="http://path.to/script.js"></script>
Share Improve this question edited Jul 30, 2009 at 2:05 Sinan Ünür 118k15 gold badges200 silver badges343 bronze badges asked Jul 30, 2009 at 1:08 Paul SweeneyPaul Sweeney 3223 silver badges7 bronze badges 1
  • stackoverflow./questions/1017424/… – Fabien Ménager Commented Jul 30, 2009 at 6:34
Add a ment  | 

4 Answers 4

Reset to default 4

Yep. Added bonus: I convert the query string parameters into a more usable javascript hash.

HTML:

<script src="script.js?var1=something&var2=somethingelse" type="text/javascript"></script>

script.js:

var scriptSource = (function() {
    var scripts = document.getElementsByTagName('script');
    return scripts[scripts.length - 1].src
}());

var params = parseQueryString(scriptSource.split('?')[1]);

params.var1; // 'something'
params.var2; // 'somethingelse'

// Utility function to convert "a=b&c=d" into { a:'b', c:'d' }
function parseQueryString(queryString) {
    var params = {};
    if (queryString) {
        var keyValues = queryString.split('&');
        for (var i=0; i < keyValues.length; i++) {
            var pair = keyValues[i].split('=');
            params[pair[0]] = pair[1];
        }
    }
    return params;
}

This method should only be used if the varaibles would determine what JavaScript code was loaded (e.g., with the request being processed by PHP, dynamically building the JS file).

If you want to pass information to JavaScript code, use functions or variables in the code after it is loaded.

error.fileName will tell you the file that a script is from (not sure if it works in every browser; I've tested it in Firefox & Opera)

var filename = (new Error).fileName;

In order to do something like that you'd need to use a server side language to render the JS for you.

I wouldn't remend it.

本文标签: Is there any analogue in Javascript to the FILE variable in PHPStack Overflow