直接从JavaScript访问GET?

jhdbpxl9  于 2022-12-21  发布在  Java
关注(0)|答案(9)|浏览(104)

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

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

但也许更简单,有没有直接从JS做的方法?

hgb9j2n6

hgb9j2n61#

你看

window.location.search

它将包含如下字符串:第一个月
要将其转化为一个对象,只需进行一些拆分:

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
bf1o4zei

bf1o4zei2#

还有一个想法:

<script type="text/javascript">

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

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

</script>
uurity8g

uurity8g3#

我知道这个主题已经很老了,但是我想分享我自己的ES6 JavaScript $_GET解决方案。

一个内衬

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()arrow functionscomma operatordestructuring assignment和 * 短路评估 * 的MDN文档。
因此,对于google.com/webhp?q=foo&hl=en&source=lnt&tbs=qdr%3Aw&sa=X&ved=&biw=12这样的URL,我们有一个对象:

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

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

URL搜索参数()

现在我们在新的浏览器中也有URLSearchParams(),它可以让你做一些事情:

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

2guxujil4#

我猜你是这么想的

<script type="text/javascript">

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

</script>

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

p1tboqfb

p1tboqfb5#

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

dxxyhpgq6#

正如其他人所解释的,您可以从JS中解析页面URL以获取变量。
您也可以在提交值的页面中使用AJAX,这实际上取决于您传递并返回给用户的信息类型。(这绝对不是更简单或更直接的方法,只是一种替代方法)

polkgigr

polkgigr7#

我用这个来处理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]);
    })();
q0qdq0h2

q0qdq0h28#

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

6mzjoqzu9#

据我所知:URLSearchParams函数是一个广泛使用的内置函数,它使您能够将所有当前查询参数获取到单个对象中。然后,您可以单独访问这些参数作为$_GET的替换,或者您可以通过foreach对其进行循环以使其成为一个数组。

/* Example - Accessing a property with using URLSearchParams in place of $_GET */

const params = new URLSearchParams(window.location.search);

// Expected Output: (string) "true"
console.log(params.get("is_the_cake_a_lie"));
/* Example - Creating a $_GET array using URLSearchParams */
const params = new URLSearchParams(window.location.search);
window.$_GET = {};

for (const [key, value] of params.entries()) {
    window.$_GET[key] = value;
}

// Expected Output: (object) { "is_the_cake_a_lie": "true" }, (string) "true"
console.log(window.$_GET, window.$_GET["is_the_cake_a_lie"]);

参考:https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

相关问题