Reputation: 12044
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 ?
Upvotes: 0
Views: 18303
Reputation: 21
You can change any element's src
using this in your JavaScript:
let myElement = (document.getElementById("myElementHTMLId").src =
"some string" + myVariable + "some string");
Upvotes: 0
Reputation: 7440
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.
Upvotes: 0
Reputation: 64526
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.
Upvotes: 2
Reputation: 1074295
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>
Upvotes: 8
Reputation: 3769
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);
Upvotes: 3
Reputation: 11561
Use a server-side language like PHP. That src
attribute is not part of the Javascript. Only the code inside the script
element.
Upvotes: 1