如何使用 JavaScript 对 PHP GET 变量运行 if 语句?
我在 snippr 上找到了一个不错的小脚本(http://snipplr.com/view.php? codeview&id=799) 为我提供了关联数组中的 GET 变量。
// Read a page's GET URL variables and return them as an associative array.
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;
}
var get = getUrlVars();
我试图检查是否设置了某个 GET 变量以及该值是否为“搜索”。由于某种原因,即使不满足条件,我的代码也无法捕获 If 语句并发出警报。
if((get['search_housing']) = 'search') {
alert('this works');
}
我不知道为什么它不尊重我的 If 声明。我的代码有问题吗?
I found a nice little script on snippr(http://snipplr.com/view.php?codeview&id=799) that gives me the GET variables in an associative array.
// Read a page's GET URL variables and return them as an associative array.
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;
}
var get = getUrlVars();
I am trying to check to see if a certain GET variable is set and if the value is 'search'. For some reason my code is not catching the If statement and alerting even if the condition is not met.
if((get['search_housing']) = 'search') {
alert('this works');
}
I'm not sure why it's not respecting my If statement. Is there something wrong with my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
=
运算符设置值。您正在寻找
==
,它比较值:The
=
operator sets the value.You're looking for
==
, which compares values:if((get['search_housing']) == 'search') {
DOUBLE 等于!
if((get['search_housing']) == 'search') {
DOUBLE equals!
也许需要是这样的:
看,
=
意味着您正在尝试将“search”分配给 get[]。Maybe it needs to be this:
See, the
=
would mean you are trying to assign 'search' to the get[].尝试使用 gup 代替。您发现的代码看起来不太健壮。您可能想要对返回值进行转义,因为您正在比较结果。
Try gup instead. That code you found doesn't look very robust. You probably want to unescape the returned value because you are comparing the results.