获取查询字符串值并将其显示在我的html页面中 [英] Get the query string value and display it in my html page
问题描述
重定向到home.html页面后,我可以看到我在上一页中给出的查询字符串值。
After redirecting to home.html page, i can see the querystring values which i had given in the previous page.
Home.html?FirstName=dd&LastName=ee&smtButton=Submit
我得到的结果为:
firstname = undefined
lastname = undefined
age = undefined
任何人都可以帮助我解决这个问题?
Could anyone help me to solve this?
JS:
function getParams() {
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx + 1, document.URL.length).split('&');
for (var i = 0; i < pairs.length; i++) {
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
推荐答案
在函数内部 function getParams ()
你被声明为变量 var params = new Array();
,我认为这会让你感到困惑
Inside your function function getParams()
you are declared variable var params = new Array();
, I think this makes confusion for you
如果找到匹配项,则指定了url param,如 params [nameVal [0]] = nameVal [1];
,这实际上并没有增加值到数组对象。所以 params.length
是 0 。但它将作为数组是对象的实例..即 params instanceof Object
是 true
if a match is found , you assigned url param like params[nameVal[0]] = nameVal[1];
, this actually not adding value into array object. so params.length
is 0 .but it will works as array is instance of object .. ie params instanceof Object
is true
所以换成基本对象..以避免混淆
so change into basic object .. to avoid confusion
function getParams() {
var idx = document.URL.indexOf('?');
var params = {}; // simple js object
.. here goes other code
}
和对象键区分大小写,因此 FirstName
将起作用..
and object key is case sensitive, so FirstName
will work ..
firstname = unescape(params["FirstName"]);
打印所有值试试这个
params = getParams();
for( var i in params ){
console.log( i , params[i] );
}
它将打印
FirstName dd
LastName ee
smtButton Submit
我修改了你的getParams代码
and I have modified your getParams code
function getParams() {
var params = {},
pairs = document.URL.split('?')
.pop()
.split('&');
for (var i = 0, p; i < pairs.length; i++) {
p = pairs[i].split('=');
params[ p[0] ] = p[1];
}
return params;
}
这篇关于获取查询字符串值并将其显示在我的html页面中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!