jQuery等效于isset($ _ GET ['var'])

时间:2012-04-27 17:52:04

标签: jquery

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

等效PHP:

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

3 个答案:

答案 0 :(得分: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
}

如果您想使用变量:

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

答案 1 :(得分:1)

像这样?

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

答案 2 :(得分:0)

location.search != ""

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

http://www.w3schools.com/jsref/prop_loc_search.asp,location.search返回网址的“查询部分”,来自“?”符号向前。因此,对于页面http://www.mysite.com/page?query=3,location.search为?query=3。对于http://www.google.com/,location.search是一个空字符串。

相关问题