Access GET directly from JavaScript?

走远了吗. 提交于 2019-11-26 20:47:08

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

Here's another idea:

<script type="text/javascript">

var $_GET = <?php echo json_encode($_GET); ?>;

alert($_GET['some_key']);
// or
alert($_GET.some_key);

</script>

I suppose you were thinking this:

<script type="text/javascript">

    var to = "<?= $_GET['to']; ?>";
    var from = "<?= $_GET['from']; ?>";

</script>

...this would just be syntax-correction of your idea :)

James Donohue

I know this topic is old, but I want to share my own ES6 optomized solution for $_GET in JavaScript. It seems all of the more popular questions on the subject are locked from contributions by SO newbies, so here it is:

One Liner

window.$_GET = location.search.substr(1).split("&").reduce((o,i)=>(u=decodeURIComponent,[k,v]=i.split("="),o[u(k)]=v&&u(v),o),{});

I'd love to link you all to the MDN documentation on array.reduce(), arrow functions, the comma operator, destructuring assignment, and short-cicuit evaluation but, alas, another SO newbie restriction.

For a URL like google.com/webhp?q=foo&hl=en&source=lnt&tbs=qdr%3Aw&sa=X&ved=&biw=12 you have an object:

$_GET = {
   q: "foo",
   hl: "en",
   source: "lnt",
   tbs: "qdr:w",
   sa: "X",
   ved: "",
   biw: "12"
}

and you can do things like $_GET.q or $_GET['biw'] to get what you need. Note that this approach replaces duplicated query parameters with the last-given value in the search string, which may be undesired/unexpected

URLSearchParams()

Now we also have URLSearchParams() in (most) newer browsers, which lets you do things like:

window.$_GET = new URLSearchParams(location.search);
var value1 = $_GET.get('param1');

As others have explained you can parse page URL from JS to get the variables.

You could also use AJAX in the page which submits the values. It really depends on what kind of information you're passing and then returning back to the user. (It's definitely not simpler or more direct way of doing it, just an alternative approach)

i use this one for Get request (like $_GET in php):

  var urlParams;
  (window.onpopstate = function () {
    var match,
          pl     = /\+/g,  Regex for replacing addition symbol with a space
           search = /([^&=]+)=?([^&]*)/g,
          decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
           query  = window.location.search.substring(1);
       urlParams = {};
       while (match = search.exec(query))
        urlParams[decode(match[1])] = decode(match[2]);
    })();
document.get = function (d1,d2,d3) {
var divider1 = (d1 === undefined ? "?" : d1);
var divider2 = (d2 === undefined ? "&" : d2);
var divider3 = (d3 === undefined ? "=" : d3);
var url = window.location.href; //the current url
var pget = url.split(divider1)[1]; //slit the url and assign only the part after the divider 1
var pppget = {}; //define the contenitor object
if (pget.search(divider2) > -1) { //control if there is variable other than the first (?var1=a&var2=b) the var2 in this example
    var ppget = pget.split(divider2); //split the divider2 
    for (i = 0;i==ppget.lenght; i++) { //start a for and stop it when i == at object length
        if (ppget[i].search(divider3) > -1) { //control if is an empty var 
            psget = ppget[i].split(divider3);//if is split in 2 part using divider 3
            pppget[psget[0]] = psget[1];//assign to the object the value of first element and for value the second value  ex {var1=a,...}  
        } else {//if is a empty var (?var1&...)
            pppget[ppget[i]] = "";//assign only the value of first element with value a blank string
        }
    }
} else {//if the url don't contain other variable 
    if (pget.search(divider3) > -1) { //control if is an empty var 
        var ppget = pget.split(divider3);//if is split in 2 part using divider 3
        pppget[ppget[0]] = ppget[1];//assign to the object the value of first element and for value the second value  ex {var1=a}  
    } else {//if is a empty var (?var1)
        pppget[pget] = "";//assign only the value of first element with value a blank string
    }
}
return pppget;
/* return the object 
 * the use of the function is like this $_GET=document.get()
 * echo $_GET[var]
 * or use custom divider the default is setted for php standard divider
 */};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!