2012-04-27 36 views
4

我现在有一个jQuery的功能,我需要知道是否有任何GET数据存在。我不需要来自查询字符串的数据,只是是否有或者不运行两个函数之一。

等效PHP:

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

可能的重复:http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript – AndrewR 2012-04-27 17:53:56

+0

你应该补充说你正在使用mod_rewrite。事实上,我认为这使得这个问题在客户端无法解决。 – Ord 2012-04-27 18:22:47

回答

4

你将不得不尝试类似的措施:(你不必使用变量,但你可以的,如果你想)

$.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 
} 

如果你想使用的变量:如果有任何GET参数

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

这样吗?

if (yourUrlStringVar.indexOf('?')>-1) { 
    return true; 
} else { 
    return false; 
} 
0
location.search != "" 

将返回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是一个空字符串。

+0

我正在使用mod_rewrite,因此不幸的是,这似乎不适用于这种情况。 – lethalMango 2012-04-27 17:59:11

+0

在这种情况下,我不确定您可以访问GET参数。从客户端,你看到的只是你要求的URL。如果这与服务器端正在使用的URL不同,那么JavaScript将忽略这一点。 – Ord 2012-04-27 18:04:20