Javascript get URL parameters

I need for a project to have two main framework handling both different content.
But, both of them are using the same server side, which means they got some data in common. In this case using iframe looks to be a valuable idea.

As the two framework are both full client side, I was needing to share data threw url, so after searching on internet, and find many bad way of doing this, I extend an existing code, to integrate many pitfall correction:

/**
 * Handling url parameter parsing
 *
 * @return {Object} The urlParameter contains a list of key/value with url param inside key, and url value inside value
*/
var urlParameter = (function() {
	// Convert urlencoded param into normal one
	function __decode(q) {
		return decodeURIComponent((q+"").replace(/\+/g, "%20"));
	};

	var content = {},
		vars    = window.location.search.substring(1).split("&"),
		i       = vars.length;

	while(i--) {
		var pair = vars[i].split("=");

		// If case of wrong split, we recreate the missing value
		if(pair.length > 2) {
			var arr = pair.slice();
			arr.shift();
			pair = [ pair[0], arr.join("=") ];
		}

		// We url decode content
		pair[0] = __decode(pair[0]);
		pair[1] = __decode(pair[1]);

		// Remove array type parameter
		var pos = pair[0].indexOf("[]");
		if(pos >= 0) {
			pair[0] = pair[0].substring(0, pos);
		}

		// If first entry with this name
		if(typeof(content[pair[0]]) === "undefined") {
			content[pair[0]] = pair[1];

		// If second entry with this name
		} else if(typeof(content[pair[0]]) === "string") {
			var arr = [ content[pair[0]], pair[1] ];
			content[pair[0]] = arr;
			// If third or later entry with this name

		} else {
			content[pair[0]].push(pair[1]);
		}
	}

	return content;
})();

This handle most of cases, including array parameter type, and url decode one. You can use it like this:

Quite simple !

Publicités

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s

%d blogueurs aiment cette page :