Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access GET directly from JavaScript?

I suppose I could use PHP to access $_GET variables from JavaScript:

<script>
var to = $_GET['to'];
var from = $_GET['from'];
</script>
<script src="realScript" type="text/javascript"></script>

But perhaps it's even simpler. Is there a way to do it directly from JS?

like image 261
Nick Heiner Avatar asked Oct 18 '09 23:10

Nick Heiner


People also ask

Can I access database with JavaScript?

JavaScript can't directly access the database. You'll need to have some server-side component that takes requests (probably via HTTP), parses them and returns the requested data.

How do you declare a private variable in JavaScript?

Alternatively, we may also use the “this” keyword to make method (function) calls to stick to the main method itself which thus makes the variables private. The main idea for using the “this” keyword is just to make things directly visible that is making methods directly accessible.


1 Answers

Look at

window.location.search

It will contain a string like this: ?foo=1&bar=2

To get from that into an object, some splitting is all you need to do:

var parts = window.location.search.substr(1).split("&");
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
    var temp = parts[i].split("=");
    $_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}

alert($_GET['foo']); // 1
alert($_GET.bar);    // 2
like image 148
nickf Avatar answered Oct 13 '22 09:10

nickf