0

This works:

<script src="chat/script.php?room=1&username=John&draggable=1"></script>

and this does not:

<script>
var username="John";
</script>  
<script src="chat/script.php?room=1&username="+username+"&draggable=1"></script>

Any idea how to fix that ?

yarek
  • 11,278
  • 30
  • 120
  • 219

6 Answers6

8

Well, you can do that using client-side code, but not using HTML:

<script>
var username="John";
var script = document.createElement('script');
script.src = "chat/script.php?room=1&username="+username+"&draggable=1";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
</script>  
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Indeed, your variable username is a JavaScript variable. Outside the <script> tag, HTML doesn't know about it. You would need to insert the <script> tag from within JavaScript. this post describes how to do that.

In your case, it would be:

var my_script = document.createElement('script');
my_script.setAttribute('src','chat/script.php?room=1&username=' + username + '&draggable=1');
document.head.appendChild(my_script);
Community
  • 1
  • 1
EyasSH
  • 3,679
  • 22
  • 36
2

The content of the script tag is executed, nothing in its attributes will be executed. You can dynamically add a script tag like so:

var username="John";
var s = document.createElement('script');
s.src = "chat/script.php?room=1&username="+username+"&draggable=1";
documennt.getElementsByTagName("head")[0].appendChild(s);

This creates a new script element, sets the src property, and then inserts it into the HTML <head> tag.

MrCode
  • 63,975
  • 10
  • 90
  • 112
1

Use a server-side language like PHP. That src attribute is not part of the Javascript. Only the code inside the script element.

DanMan
  • 11,323
  • 4
  • 40
  • 61
0

Another method is to use document.write method as following:

var username = "John";
document.write( "<script src=\"chat/script.php?room=1&username=" + username 
                + "&draggable=1\"><" + "/script>" );

Note that i have break the </script> part such that it doesn't assumed as end closing tag of your main script block! the \"is used to escape the double quotation mark inside the string.

S.Serpooshan
  • 7,608
  • 4
  • 33
  • 61
0

You can change any element's src using this in your JavaScript:

let myElement = (document.getElementById("myElementHTMLId").src =
"some string" + myVariable + "some string");
  • Another option is to use [setAttribute](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute) Example: `myElement.setAttribute('src', 'srcValue');` – pauldcomanici Apr 19 '20 at 16:41
  • Not an answer, because they ask how to load a script with a dynamic url, not how to change url on an already loaded script – zoran404 Apr 19 '20 at 17:02