如何从GET参数中获取值? [英] How to get the value from the GET parameters?

查看:144
本文介绍了如何从GET参数中获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些GET参数的网址如下:

I have a URL with some GET parameters as follows:

www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 

我需要得到整个值 c 。我试图读取URL,但我只得到 m2 。如何使用JavaScript执行此操作?

I need to get the whole value of c. I tried to read the URL, but I got only m2. How do I do this using JavaScript?

推荐答案

JavaScript本身没有内置处理查询字符串参数的内容。

JavaScript itself has nothing built in for handling query string parameters.

在(现代)浏览器中,您可以使用 网址对象;

In a (modern) browser you can use the URL object;

var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);

对于旧浏览器(包括Internet Explorer),您可以使用此polyfill 或此答案的原始版本中的代码早于 URL

For older browsers (including Internet Explorer), you can use this polyfill or the code from the original version of this answer that predates URL:

您可以访问 location.search ,这将从到URL末尾的字符或片段标识符的开头(#foo),以先到者为准。

You could access location.search, which would give you from the ? character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.

然后你可以解析它:

function parse_query_string(query) {
  var vars = query.split("&");
  var query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    var key = decodeURIComponent(pair[0]);
    var value = decodeURIComponent(pair[1]);
    // If first entry with this name
    if (typeof query_string[key] === "undefined") {
      query_string[key] = decodeURIComponent(value);
      // If second entry with this name
    } else if (typeof query_string[key] === "string") {
      var arr = [query_string[key], decodeURIComponent(value)];
      query_string[key] = arr;
      // If third or later entry with this name
    } else {
      query_string[key].push(decodeURIComponent(value));
    }
  }
  return query_string;
}

var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);

您可以从当前页面的URL获取查询字符串:

You can get the query string from the URL of the current page with:

var query = window.location.search.substring(1);
var qs = parse_query_string(query);

这篇关于如何从GET参数中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆