获取 Url 字符串参数作为 JSON 对象

Get Url string parameter as JSON object

我想知道是否可以使用 window 对象将 url 参数作为 JSON 对象获取。

例如。我有 url "/#/health?firstName=tom&secondName=Mike"

并获取值 {"firstName": "tom", "secondName": "Mike"}

我试图探索 window 对象,但找不到任何帮助。

我想我可以尝试解析字符串 firstName=tom&secondName=Mike 并将其转换为 json 但这看起来不是一个好方法。顺便说一句,如果有聪明的解析方法,那也将不胜感激。

如果我需要提供更多信息,请告诉我。

在 Angular 中,您可以通过以下方式获得 URL:

this.router.url

获得 URL 后,您应该使用非常流行的(每周 14 次 mill 下载)npm qs 模块:

var qs = require('qs');
var obj = qs.parse('firstName=tom&secondName=Mike');

returns:

{
  firstName: 'tom'
  secondName: 'mike'
}

直接使用javascript先获取params再转换为对象:

<script type="text/javascript">

    // params will be an object with key value pairs based on the url query string
    var params = paramsToObject();
    console.log(params);

    // Get the parameters by splitting the url at the ?
    function getParams() {
        var uri = window.location.toString();
        if (uri.indexOf("?") > 0) {
            var params = uri.substring(uri.indexOf("?") + 1, uri.length);
            return params;
        }
        return "";
    }

    // Split the string by & and then split each pair by = then return the object
    function paramsToObject() {
        var params = getParams().split("&");
        var obj = {};

        for (p in params) {
            var arr = params[p].split("=");
            obj[arr[0]] = arr[1];
        }

        return obj;
    }
</script>

如果使用Angular: 您可以使用 danday74.

的答案中建议的 qs npm 模块
const str = 'abc=foo&def=%5Bbar%5D&xyz=5'

    // reduce takes an array and reduces it into a single value
    const nameVal = str.split('&').reduce((prev, curr) => {
    // see output here in console for clarity:
    console.log('curr= ', curr, ' prev = ', prev)
    prev[decodeURIComponent(curr.split('=')[0])] = decodeURIComponent(curr.split('=')[1]);
    return prev;
}, {});

// invoke 
console.log(nameVal);