如何获取JavaScript中的URL参数?
How to get URL parameters in JavaScript?
我正在使用 Vue,但是我没有使用 vue-router。
如何获取URI参数?
我找到了一种使用 root el 属性 获取 URI 的方法。
但是有没有什么合适的方法来获取我想发送的参数
后端并从服务器获取响应并显示它。
路由属性存在于 this.$route
。
this.$router
是路由器对象的实例,它给出了路由器的配置。
你可以用这个查询当前的路线。$route.query
由于您没有使用 vue-router
,我认为您将无法访问您的参数。所以你唯一的机会是使用 URL api 作为:
const URL = new URL(window.location.href);
const getParam = URL.searchParams.get('foo');
这将为您提供 ?foo=bar
中 foo 的值
或者,您也可以这样做。
new Vue({
el: '#app',
data () {
return {
params: window.location.href.substr(window.location.href.indexOf('?'))
}
},
methods: {
getParam (p) {
let param = new URLSearchParams(this.params);
if(param.has(p)){
return param.get(p)
}else{
false
}
}
},
})
现在,只需使用 getParam('foo')
获取参数
我们也暂时不用vue router。我们使用以下脚本来解析 args。
var args = {};
var argString = window.location.hash;
//everything after src belongs as part of the url, not to be parsed
var argsAndSrc = argString.split(/src=/);
args["src"] = argsAndSrc[1];
//everything before src is args for this page.
var argArray = argsAndSrc[0].split("?");
for (var i = 0; i < argArray.length; i++) {
var nameVal = argArray[i].split("=");
//strip the hash
if (i == 0) {
var name = nameVal[0];
nameVal[0] = name.slice(1);
}
args[nameVal[0]] = decodeURI(nameVal[1]);
}
您可以使用window.location.search获取URL参数:
const queryString = window.location.search;
console.log(queryString);
// ?product=troussers&color=black&newuser&size=s
对于查询字符串的解析参数,使用URLSearchParams:
const urlParams = new URLSearchParams(queryString);
有关详细信息,请阅读这篇文章 tutorial。
我正在使用 Vue,但是我没有使用 vue-router。
如何获取URI参数?
我找到了一种使用 root el 属性 获取 URI 的方法。
但是有没有什么合适的方法来获取我想发送的参数 后端并从服务器获取响应并显示它。
路由属性存在于 this.$route
。
this.$router
是路由器对象的实例,它给出了路由器的配置。
你可以用这个查询当前的路线。$route.query
由于您没有使用 vue-router
,我认为您将无法访问您的参数。所以你唯一的机会是使用 URL api 作为:
const URL = new URL(window.location.href);
const getParam = URL.searchParams.get('foo');
这将为您提供 ?foo=bar
或者,您也可以这样做。
new Vue({
el: '#app',
data () {
return {
params: window.location.href.substr(window.location.href.indexOf('?'))
}
},
methods: {
getParam (p) {
let param = new URLSearchParams(this.params);
if(param.has(p)){
return param.get(p)
}else{
false
}
}
},
})
现在,只需使用 getParam('foo')
我们也暂时不用vue router。我们使用以下脚本来解析 args。
var args = {};
var argString = window.location.hash;
//everything after src belongs as part of the url, not to be parsed
var argsAndSrc = argString.split(/src=/);
args["src"] = argsAndSrc[1];
//everything before src is args for this page.
var argArray = argsAndSrc[0].split("?");
for (var i = 0; i < argArray.length; i++) {
var nameVal = argArray[i].split("=");
//strip the hash
if (i == 0) {
var name = nameVal[0];
nameVal[0] = name.slice(1);
}
args[nameVal[0]] = decodeURI(nameVal[1]);
}
您可以使用window.location.search获取URL参数:
const queryString = window.location.search;
console.log(queryString);
// ?product=troussers&color=black&newuser&size=s
对于查询字符串的解析参数,使用URLSearchParams:
const urlParams = new URLSearchParams(queryString);
有关详细信息,请阅读这篇文章 tutorial。