Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript url variables

I have

<script type="text/javascript" src="http://doamin.com/js/whatever.js?ref=images"></script>

Note the ref=images at the end of the url. My questions is, how do i get the ref variable from the url and use it inside this same js file.

like image 921
Pinkie Avatar asked Oct 20 '11 03:10

Pinkie


3 Answers

Simplifying mrtsherman's idea, just find the script with the correct src (from within whatever.js):

var whatever = $('script[src*=http://domain.com/js/whatever.js]')

if (whatever.length){
    var ref = whatever.attr('src').match(/\?ref=(.*)/)
    if (ref && ref[1]){
        ref = ref[1] // ref == 'images'
    }
}

update: since you just want to output something from PHP and use it in your script, you have a much better option:

<script id="whatever" src="http://domain.com/whatever.js" data-ref="images"></script>

Then from your script (assuming jQuery >= 1.4):

var ref = $('#whatever').data('ref') // "images"

This is the recommended and standard way to get data from server-side in your client scripts.

See http://html5doctor.com/html5-custom-data-attributes/ and http://dev.w3.org/html5/spec/elements.html#embedding-custom-non-visible-data

like image 75
Ricardo Tomasi Avatar answered Nov 15 '22 06:11

Ricardo Tomasi


If whatever.js is a just js file, you can't.

If it is just a request uri and using the server side script to output the javascript content, you can get the variable from the get parameter.

If you want to pass the variable to the whatever.js, you can just define the variable before include whatever.js and then use the variable in whatever.js.

<script type="text/javascript">
<!--// 
  ref = 'images';
//-->
</script>
like image 30
xdazz Avatar answered Nov 15 '22 06:11

xdazz


I don't know of a way to get the src attribute for only the current blocks script element. But you could get all scripts on the page and then parse them.

//untested
var scripts = $('script[src]');
//loop through scripts and somehow identify the one that is yours
for (var script in scripts) {
  if (myscript) {
    var refvalue = getRef($(script).attr('src'), 'ref');
  }
}

//gup the parameter
function getRef(url, name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

Hopefully this is enough to go on

like image 45
mrtsherman Avatar answered Nov 15 '22 06:11

mrtsherman