How do I simply get GET
and POST
values with JQuery?
What I want to do is something like this:
$('#container-1 > ul').tabs().tabs('select', $_GET('selectedTabIndex'));
GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
The jQuery post() method sends asynchronous http POST request to the server to submit the data to the server and get the response. Syntax: $. post(url,[data],[callback],[type]);
For GET parameters, you can grab them from document.location.search
:
var $_GET = {}; document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () { function decode(s) { return decodeURIComponent(s.split("+").join(" ")); } $_GET[decode(arguments[1])] = decode(arguments[2]); }); document.write($_GET["test"]);
For POST parameters, you can serialize the $_POST
object in JSON format into a <script>
tag:
<script type="text/javascript"> var $_POST = <?php echo json_encode($_POST); ?>; document.write($_POST["test"]); </script>
While you're at it (doing things on server side), you might collect the GET parameters on PHP as well:
var $_GET = <?php echo json_encode($_GET); ?>;
Note: You'll need PHP version 5 or higher to use the built-in json_encode
function.
Update: Here's a more generic implementation:
function getQueryParams(qs) { qs = qs.split("+").join(" "); var params = {}, tokens, re = /[?&]?([^=]+)=([^&]*)/g; while (tokens = re.exec(qs)) { params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]); } return params; } var $_GET = getQueryParams(document.location.search);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With