Baz
Baz

Reputation: 13135

Global Variable Use within the Script Tag's Source Attribute

I run the following JavaScript code which gives my the list of parameters from the client as well as calling a Google fusion table SQL statement which supplies its response to the callback function handleResponse.

<script>

  // get parameter list
  var url = window.location.toString();
  url.match(/\?(.+)$/);
  var params = RegExp.$1;
  var params = params.split("&");
  var queryStringList = {};
  for(var i=0;i<params.length;i++)
  {
    var tmp = params[i].split("=");
    queryStringList[tmp[0]] = unescape(tmp[1]);
  }

  // callback function
  function handleRespose(response)
  {
  }
</script>
<script src="https://www.googleapis.com/fusiontables/v1/query?sql=SELECT data from table&key=myKey&callback=handleRespose"></script>

My question is, how can I use queryStringList like this:

<script src="https://www.googleapis.com/fusiontables/v1/query?sql=SELECT " + queryStringList["data1"] + "from table&key=myKey&callback=handleRespose"></script>

Upvotes: 0

Views: 876

Answers (1)

Peter-Paul van Gemerden
Peter-Paul van Gemerden

Reputation: 7011

You'll have to load the new JS file from JavaScript. For example:

var fusiontables = document.createElement("script");
fusiontables.setAttribute("src", "https://www.googleapis.com/fusiontables/v1/query?sql=SELECT " + queryStringList["data1"] + "from table&key=myKey&callback=handleRespose");

document.getElementsByTagName("head")[0].appendChild(fusiontables);

This will programmatically create a new <script> element and inject it into the page. Note that the variable doesn't need to be global to do this.

If you put this in a function, you could use it like this:

// loadscript.js
function loadscript(url) {
    var script = document.createElement("script");
    script.setAttribute("src", url);
    document.getElementsByTagName("head")[0].appendChild(script);
}
<!-- page.html -->
<script src="loadscript.js"></script>
<script>
    var queryStringList = {};
    // ... Do stuff to fill queryStringList ...

    var url = "https://www.googleapis.com/fusiontables/v1/query?sql=SELECT " + queryStringList["data1"] + "from table&key=myKey&callback=handleRespose";
    loadscript(url);
</script>

Upvotes: 1

Related Questions