Created
February 26, 2015 18:08
-
-
Save johntron/27146f02502dc6bd0f13 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script> | |
<a href="asdf?foo=bar">clickme</a> | |
<a href="asdf?doo=gar">clickme2</a> | |
<script> | |
var $as = document.querySelectorAll('a'); | |
[].forEach.call($as, function ($a) { | |
$($a).on('click', post); | |
}); | |
function post(e) { | |
e.preventDefault(); | |
var $a = e.target; | |
var data = query_string_to_object($a.href.split('?')[1]); | |
$.post($a.href, data, function (data) { | |
document.body.innerHTML = data; | |
}); | |
} | |
function query_string_to_object(str) { | |
if (typeof str !== 'string') { | |
return {}; | |
} | |
str = str.trim().replace(/^(\?|#)/, ''); | |
if (!str) { | |
return {}; | |
} | |
return str.trim().split('&').reduce(function (ret, param) { | |
var parts = param.replace(/\+/g, ' ').split('='); | |
var key = parts[0]; | |
var val = parts[1]; | |
key = decodeURIComponent(key); | |
// missing `=` should be `null`: | |
// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters | |
val = val === undefined ? null : decodeURIComponent(val); | |
if (!ret.hasOwnProperty(key)) { | |
ret[key] = val; | |
} else if (Array.isArray(ret[key])) { | |
ret[key].push(val); | |
} else { | |
ret[key] = [ret[key], val]; | |
} | |
return ret; | |
}, {}); | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment