开发者

Passing key-value pairs to a JavaScript file

Can you pass key-value pairs to开发者_StackOverflow中文版 a JavaScript file like that:

<script type="text/javascript" src="http://www.example.com/script.js?key=value"></script>


That technique is used by scriptaculous (see line 54):

<script type="text/javascript" src="scriptaculous.js?load=effects,dragdrop">
</script>

You can achieve this by inspecting the source of the script elements on your page, I leave you a framework independent function:

function getScriptVariable(scriptName, key) {
  var scripts = document.getElementsByTagName('script'),
      n = scripts.length, scriptSource, i, r;

  for (i = 0; i < n; i++) {
    scriptSource = scripts[i].src;
    if(scriptSource.indexOf(scriptName)>=0) {
      r = new RegExp("[\\?&]"+key+"=([^&#]*)");
      var keyValues = r.exec(scriptSource);
      return keyValues[1];
    }
  }
}

Then you can embed a script in the way you want:

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

And use the above function in this way:

var value = getScriptVariable('myScript.js', 'myKey'); // "myValue"


Not easily, unless you want them to be processed by server-side code that generates Javascript.

However, you can define variables in an earlier script block as parameters.

For example:

<script type="text/javascript">
    var key = value;
</script>

<script type="text/javascript" src="http://www.example.com/script.js></script>

You can then use the key variable in script.js just like any other variable.

EDIT: As Upper Stage pointed out, it would be a better idea to put the parameters inside their own namespace.

For example:

<script type="text/javascript">
    var MyScriptParameters = {
        param1: 123,
        param2: "Hello",
        param3: new Date,
        param4: function(text) { ... }
    };
</script>

You could then write MyScriptParameters.param2 in script.js (Or in any other script on the page)


Not like that. The above will perform a GET request on the HTTP server with parameters key=value. Those won't (normally) impact on the resource script.js being returned to you (which is what the above is asking for).


to add to SLaks answer, json encoding the data handles your escaping needs. in php: json_encode()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜