我有一个这样的链接:
http://localhost:8162/UI/Link2.aspx?txt_temp=123abc
我想获取值 123abc
。我已经关注了这个How can I get query string values in JavaScript?和
jquery get querystring from URL
$(document).ready(function () {
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
onload = function () {
alert(getParameterByName('txt_temp'));
alert(getUrlVars()["txt_temp"]);
}
});
但它不起作用。
最佳答案
假设您的 URL 包含许多参数,例如:-
"http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"
然后在 js 中你可以这样做:
var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"
或
var url = window.location.href
然后将主 url 拆分为:
hashes = url.split("?")[1]
//hashes 保存此输出 "txt_temp=123abc&a=1&b=2"
然后你又可以通过&分割得到单独的参数
编辑
检查这个例子:
function getUrlVars() {
var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2";
var vars = {};
var hashes = url.split("?")[1];
var hash = hashes.split('&');
for (var i = 0; i < hash.length; i++) {
params=hash[i].split("=");
vars[params[0]] = params[1];
}
return vars;
}
输出
getUrlVars()
Object {txt_temp: "123abc", a: "1", b: "2"}
关于javascript - 如何在 Javascript 或 jQuery 中获取查询字符串参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30271461/