Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a variable inside script tag

I have a page name index.php. And I have a script variable as follows at the top of the page:

<script>
    var search_quarry = "some_test";
</script>

At the bottom of the same page I want to add this variable into the src attribute of a script tag:

<script src=NEED_TO_ADD_HERE></script>

This doesn't work:

<script src=search_quarry> </script>

Can anyone please tell me how to do this?

like image 379
Roshanck Avatar asked Jul 12 '12 18:07

Roshanck


2 Answers

You'd need to do with DOM manipulation:

var search_query = 'some_test';
s = document.createElement('script');
s.src = search_query;
document.getElementsByTagName('head')[0].appendChild(s);

or, as an alternative, though I'm not sure if this'd work:

<script id="fixme"></script>
<script type="text/javascript">
    var search_query = 'some_test';
    document.getElementById('fixme').src = search_query;
</script>
like image 192
Marc B Avatar answered Sep 27 '22 19:09

Marc B


Why would you do this? Seems like a hack to make sever code work without fixing the back end

Option 1 is with document.write

<script>
    document.write("<script src='" + search_quarry + "'></scr" + "ipt>");
</script>

Option 2 is to use createElement and appendChild

<script>
    var scr = document.createElement("script");
    scr.src = search_quarry;
    document.getElementsByTagName("head")[0].appendChild(scr);  //or use body with document onready
</script>
like image 40
epascarello Avatar answered Sep 27 '22 21:09

epascarello