Access GET directly from JavaScript?

前端 未结 7 1288
南旧
南旧 2020-11-27 20:59

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



        
7条回答
  •  悲哀的现实
    2020-11-27 21:39

    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');
    

提交回复
热议问题