jQuery对应于isset($_GET['var'])

6

我目前有一个jQuery函数,我需要知道是否存在任何GET数据。我不需要查询字符串中的数据,只需要知道是否有数据来运行其中两个函数之一。

相当的PHP代码:

if (isset($_GET['datastring'])) {
    // Run this code
} else {
    // Else run this code
}

3
可能是重复问题:https://dev59.com/nHNA5IYBdhLWcg3wmfAa您可以使用以下代码在JavaScript中获取URL查询字符串参数:function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); }使用示例:假设当前页面的URL为http://www.example.com/?pageId=1&articleId=1234,则以下代码将返回1var pageId = getParameterByName('pageId'); - AndrewR
你应该注明你正在使用mod_rewrite。事实上,我认为这使得客户端无法解决这个问题。 - Ord
3个回答

6
你需要尝试类似于以下的操作:(你不必使用变量,但如果你想用也可以)
$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}

if ($.urlParam('variable_name') != '') {  // variable_name would be the name of your variable within your url following the ? symbol
    //execute if empty
} else {
    // execute if there is a variable
}

如果您想使用变量:

// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null

2
location.search != ""

如果有任何GET参数,将返回true。

http://www.w3schools.com/jsref/prop_loc_search.asp来看,location.search返回URL的“查询部分”,即从'?'符号开始。 因此,对于页面http://www.mysite.com/page?query=3,location.search是?query=3。 对于http://www.google.com/,location.search是一个空字符串。


我正在使用mod_rewrite,所以不幸的是,它似乎对这种情况不起作用。 - lethalMango
在这种情况下,我不确定您是否可以访问GET参数。从客户端的角度来看,您只能看到您请求的URL。如果它与服务器端使用的URL不同,那么JavaScript将对此毫不知情。 - Ord

1

像这样吗?

if (yourUrlStringVar.indexOf('?')>-1) {
  return true;
} else {
  return false;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接