Return to Snippet

Revision: 51113
at September 14, 2011 22:01 by DenoteIt


Initial Code
function getJSvars(script_name, var_name, if_empty) {

	var script_elements = document.getElementsByTagName('script');

	if(if_empty == null) {var if_empty = '';}

	for (a = 0; a < script_elements.length; a++) {
		var source_string = script_elements[a].src;
		if(source_string.indexOf(script_name)>=0) {

		var_name = var_name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regex_string = new RegExp("[\\?&]"+var_name+"=([^&#]*)");
		var parsed_vars = regex_string.exec(source_string);
		if(parsed_vars == null) { return if_empty; }
		else { return parsed_vars[1]; }

		}
	}
}

Initial URL
http://posheika.net/?p=42

Initial Description
Pass variables into javascript files using query strings, and return them using getJSvars()
Example

//HTML
<script>

//return the value of "foo"
getJSvars('filename.js', 'foo');

Initial Title
Pass variables into javascript via query strings

Initial Tags
javascript, query

Initial Language
JavaScript