[英]Get Url string parameter as JSON object
我想知道是否可以使用window对象将url参数作为JSON对象获取。
对于前。 我的网址是“ /#/ health?firstName = tom&secondName = Mike”
并以{“ firstName”:“ tom”,“ secondName”:“ Mike”}的形式获取值
我试图浏览窗口对象,但找不到任何帮助。
我想我可以尝试解析字符串firstName = tom&secondName = Mike并将其转换为json,但这似乎不是一个好方法。 顺便说一句,如果有聪明的方式来解析,那也将不胜感激。
请让我知道是否需要提供更多信息。
在Angular中,您可以通过以下方式获取URL:
this.router.url
取得网址后,您应该使用非常受欢迎的(每周14次下载)npm qs模块:
var qs = require('qs');
var obj = qs.parse('firstName=tom&secondName=Mike');
返回:
{
firstName: 'tom'
secondName: 'mike'
}
使用简单的javascript首先获取参数,然后将它们转换为对象:
<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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.