我目前有一个jQuery函数,我需要知道是否存在任何GET
数据。我不需要查询字符串中的数据,只需要知道是否有数据来运行其中两个函数之一。
相当的PHP代码:
if (isset($_GET['datastring'])) {
// Run this code
} else {
// Else run this code
}
我目前有一个jQuery函数,我需要知道是否存在任何GET
数据。我不需要查询字符串中的数据,只需要知道是否有数据来运行其中两个函数之一。
相当的PHP代码:
if (isset($_GET['datastring'])) {
// Run this code
} else {
// Else run this code
}
$.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¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
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是一个空字符串。
像这样吗?
if (yourUrlStringVar.indexOf('?')>-1) {
return true;
} else {
return false;
}
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
,则以下代码将返回1
:var pageId = getParameterByName('pageId');
- AndrewR