简体   繁体   English

如何使用JavaScript在PHP GET变量上运行if语句?

[英]How can I run an if statement on a PHP GET variable using JavaScript?

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. 我在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(); 

I am trying to check to see if a certain GET variable is set and if the value is 'search'. 我正在尝试检查是否设置了某个GET变量,以及该值是否为“搜索”。 For some reason my code is not catching the If statement and alerting even if the condition is not met. 由于某种原因,即使不满足条件,我的代码也无法捕获If语句并发出警报。

if((get['search_housing']) = 'search') {
  alert('this works');
}

I'm not sure why it's not respecting my If statement. 我不确定为什么它不尊重我的If语句。 Is there something wrong with my code? 我的代码有问题吗?

The = operator sets the value. =运算符设置值。

You're looking for == , which compares values: 您正在寻找== ,它会比较值:

if((get['search_housing']) == 'search') {
  alert('this works');
}

if((get['search_housing']) == 'search') {

双等于!

Maybe it needs to be this: 也许需要这样:

if((get['search_housing']) == 'search') {
    alert('this works');
}

See, the = would mean you are trying to assign 'search' to the get[]. 看到, =表示您正在尝试为get []分配“搜索”。

Try gup instead. 请尝试使用gup That code you found doesn't look very robust. 您发现的代码看上去并不十分健壮。 You probably want to unescape the returned value because you are comparing the results. 您可能想取消对返回值的转义,因为您正在比较结果。

if (gup('search_housing') == 'search') { ... }

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
if(get('search_housing')==='search'){
  alert('test');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM