【问题标题】:Access GET directly from JavaScript?直接从 JavaScript 访问 GET?
【发布时间】:2010-12-07 20:44:51
【问题描述】:

我想我可以使用 PHP 从 JavaScript 访问 $_GET 变量:

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

但也许它更简单。有没有办法直接从 JS 做呢?

【问题讨论】:

    标签: php javascript get


    【解决方案1】:

    看看

    window.location.search
    

    它将包含这样的字符串:?foo=1&amp;bar=2

    要从中得到一个对象,你需要做的只是一些分裂:

    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
    

    【讨论】:

    • decodeURIComponent,而不是 unescape,这将导致 +s 和所有非 ASCII 字符错误。
    【解决方案2】:

    正如其他人所解释的,您可以从 JS 解析页面 URL 以获取变量。

    您也可以在提交值的页面中使用AJAX。这实际上取决于您传递什么样的信息,然后返回给用户。 (这绝对不是更简单或更直接的方法,只是一种替代方法)

    【讨论】:

      【解决方案3】:

      我猜你是这么想的:

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

      ...这只是对您的想法的语法更正:)

      【讨论】:

      • 你会想要确保你在字符串中也转义了双引号;)否则这是一个安全风险。
      • 你的意思是var to = \" ... \"
      【解决方案4】:

      这是另一个想法:

      <script type="text/javascript">
      
      var $_GET = <?php echo json_encode($_GET); ?>;
      
      alert($_GET['some_key']);
      // or
      alert($_GET.some_key);
      
      </script>
      

      【讨论】:

      • 它只是一个可以超越自身的IDEA......创建动态代码而不是数据......我♥它......
      • 另外,如果你要将 PHP 注入到 JS 中,这是最安全和最干净的方法。
      【解决方案5】:

      我将这个用于获取请求(如 php 中的 $_GET):

        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]);
          })();
      

      【讨论】:

        【解决方案6】:
        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
         */};
        

        【讨论】:

        • 你的答案应该包含对你的代码的解释和它如何解决问题的描述。
        【解决方案7】:

        我知道这个话题很老了,但我想分享我自己的 ES6 优化解决方案,用于 JavaScript 中的 $_GET。似乎所有关于这个主题的更受欢迎的问题都被 SO 新手的贡献锁定了,所以这里是:

        一个班轮

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

        我很乐意将大家链接到关于 array.reduce()箭头函数逗号运算符的 MDN 文档, 解构赋值短期评估但是,唉,另一个SO新手限制。

        对于像google.com/webhp?q=foo&amp;hl=en&amp;source=lnt&amp;tbs=qdr%3Aw&amp;sa=X&amp;ved=&amp;biw=12 这样的 URL,您有一个对象:

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

        您可以执行$_GET.q$_GET['biw'] 之类的操作来获得所需的内容。请注意,这种方法将重复的查询参数替换为搜索字符串中最后给定的值,可能是undesired/unexpected

        URLSearchParams()

        现在我们在(大多数)较新的浏览器中也有URLSearchParams(),它可以让您执行以下操作:

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

        【讨论】:

        • 不知道我的实例是否是边缘情况,但我发现我必须使用“.href”而不是“.search”,例如:window.location.href.substr(1) .split("&").reduce((o,i)=>(u=decodeURIComponent,[k,v]=i.split("="),o[u(k)]=v&&u(v), o),{});
        【解决方案8】:
        class Utils {
            static HTTP_GET(key){
                let map = this.HTTP_GET_ALL();
        
                if(map.has(key)){
                    return map.get(key);
                }else {
                    return null;
                }
            }
        
            static HTTP_GET_ALL(){
                let parts = window.location.search.substr(1).split("&");
                let map = new Map();
        
                for (let i = 0; i < parts.length; i++) {
                    let temp = parts[i].split("=");
                    map.set(decodeURIComponent(temp[0]), decodeURIComponent(temp[1]));
                }
        
                return map;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-03
          • 2023-03-16
          相关资源
          最近更新 更多