2011-12-10 47 views
5

我想使用JavaScript獲取url值,到目前爲止,我只能得到純數字,而不是字母或只是字母的混合數字。我找不到任何可以檢索字母數字的函數的實例,只是數字。我沒有使用任何非字母數字字符。我試圖通過的一個示例值是「42p316041610751874cm83p2306600132141」。使用Javascript從url參數獲取變量

function getUrlVars() 
{ 
var vars = [], hash; 
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); 
for(var i = 0; i < hashes.length; i++) 
{ 
    hash = hashes[i].split('='); 
    vars.push(hash[0]); 
    vars[hash[0]] = hash[1]; 
} 
return vars; 
} 

var first = getUrlVars()["test"]; 

任何幫助將是偉大的。謝謝。

+0

這很奇怪。你的代碼應該工作。 – Blender

+0

我試過了,它適用於我。我使用這個URL:'''http://localhost/test/index.html?test = 42p316041610751874cm83p2306600132141'''。 – FakeRainBrigand

+0

我使用jQuery Mobile作爲網站的框架,如果這很重要? – cWoolf

回答

5

下面是兩個精簡版上面的答案:

function gup (name) { 
    name = RegExp ('[?&]' + name.replace (/([[\]])/, '\\$1') + '=([^&#]*)'); 
    return (window.location.href.match (name) || ['', ''])[1]; 
} 

更容易打字,更容易處理和,恕我直言更容易閱讀。 YMMV

0

你的代碼看起來像它應該工作,我用了以下功能,如果有幫助

function getParam(name){ 
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); 
    var regexS = "[\\?&]"+name+"=([^&#]*)"; 
    var regex = new RegExp(regexS); 
    var results = regex.exec (window.location.href); 
    if (results == null) 
     return ""; 
     else 
     return results[1]; 
} 

var first = getParam("test"); 
0

你的方法應該工作。這裏是我的版本進行比較:

var o = { 
    keys: [ ], 
    values: [ ] 
} 

/* 
You could just use the window#location#search value to get the query sub-String of the currently loaded URL 

var q = window.location.search.substring(1) ; 

For now we'll use a query String from a Google search for "MDN window location" 
*/ 

q = "q=mdn+window+location&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:de:official&client=firefox-a" 

for(var i = 0 , a = q.split("&"), p ; i < a.length ; i++) { 
    p = a[i] ; 
    if( (b = p.split("=")) != null) { 
     o.keys[i] = b[0] ; 
     o.values[i] = b[1] ; 
    } 
} 


console.log("(!!) o: " + o.toSource()) ; 

3

我使用此功能,並且它的岩石。不知從哪裏我把它記住,但它是一個很好的一個:

function gup(name) { 
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); 
    var regexS = "[\\?&]" + name + "=([^&#]*)"; 
    var regex = new RegExp(regexS); 
    var results = regex.exec(window.location.href); 
    if (results == null) 
     return ""; 
    else 
     return results[1]; 
} 

如果你有一個像http://www.exmaple.com/path?p1=lkjsd234&p2=klsjd987一個網址,你可以使用:

alert(gup('p1')); // shows 'lkjsd234';