2012-01-03 144 views
1

说我有http://www.mysite.com/index.php?=332使用jQuery从url获取字符串?

是否有可能使用jQuery在?=之后检索字符串?我一直在环顾Google,发现很多Ajax和URL变量信息,这些信息似乎没有给我任何想法。

if (url.indexOf("?=") > 0) { 
    alert('do this'); 
} 
+4

首款谷歌返回结果从查询字符串值 - HTTP: //jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html – FlabbyRabbit 2012-01-03 22:57:45

+0

这甚至有效吗? '?= 332' *我想这是... * – 2012-01-03 22:58:55

+1

可能重复的[如何获得查询字符串的JavaScript?](http://stackoverflow.com/questions/2907482/how-to-get-the-查询字符串的JavaScript) – 2012-01-03 23:07:16

回答

0
var myArgs = window.location.search.slice(1) 
var args = myArgs.split("&") // splits on the & if that's what you need 
var params = {} 
var temp = [] 
for (var i = 0; i < args.length; i++) { 
    temp = args[i].split("=") 
    params[temp[0]] = temp[1] 
} 

// var url = "http://abc.com?a=b&c=d" 
// params now might look like this: 
// { 
//  a: "a", 
//  c: "d" 
// } 

你想做什么?如果您正在阅读网址,您很可能会做错。

+0

'window.location.href'应该只是'window.location.search' – epascarello 2012-01-03 23:20:21

+0

哦很酷的东西!谢谢 – 2012-01-03 23:22:13

0

这里是一段代码(不是我,不记得源)通过提供一个名称

$.urlParam = function(name){ 
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);   
if (!results) 
     { return 0; }   
return results[1] || 0; 

}