直接从JavaScript访问GET?

时间:2009-10-18 23:34:18

标签: php javascript get

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

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

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

8 个答案:

答案 0 :(得分:46)

看看

window.location.search

它将包含如下字符串:?foo=1&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

答案 1 :(得分:10)

这是另一个想法:

<script type="text/javascript">

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

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

</script>

答案 2 :(得分:4)

我想你在想这个:

<script type="text/javascript">

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

</script>

...这只是你的想法的语法纠正:)

答案 3 :(得分:2)

我知道这个话题很老,但我想在JavaScript中分享我自己的ES6优化解决方案for $ _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&hl=en&source=lnt&tbs=qdr%3Aw&sa=X&ved=&biw=12这样的网址,您有一个对象:

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

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

我将这个用于Get请求(如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 :(得分:0)

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;
    }
}

答案 7 :(得分:-1)

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
 */};