2013-01-11 53 views
-3

可能重複的URL變量:
How can I get query string values?獲得使用JS

我有這個鏈接

網址/ merchant.html ID = 45

我我試圖使用JS或JQuery來獲取ID,但沒有運氣。

我想這個代碼

var urlParams = {}; 
(function() { 
    var match, 
     pl  = /\+/g, // Regex for replacing addition symbol with a space 
     search = /([^&=]+)=?([^&]*)/g, 
     decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, 
     query = window.location.search.substring(1); 

    while (match = search.exec(query)) 
     urlParams[decode(match[1])] = decode(match[2]); 
})(); 

返回 「未定義」

什麼是代碼中的問題?

+0

'document.location.href'? – marekful

+0

不返回ID –

+1

你的代碼只是在FF linux中爲我工作,沒有任何修改... – marekful

回答

0

我寫了這個功能一段時間回來:

/** 
* Retrieves the value of a query string parameter. 
* @param string href The full URL 
* @param string key The key in the query string to search for. 
* @param variant def The default value to return if the key doesn't exist. 
* @returns variant if key exists returns the value, otherwise returns a default value. 
*/ 
function getURIParam(href, key, def) { 
    if (arguments.length == 2) def = null; 
    var qs = href.substring(href.indexOf('?') + 1); 
    var s = qs.split('&'); 
    for (var k in s) { 
     var s2 = s[k].split('='); 
     if (s2[0] == key) 
      return decodeURIComponent(s2[1]); 
    } 
    return def; 
} 

你會使用這樣的:

var href = "http://www.example.org?id=1492"; 
var id = getURIParam(href, "id", 0); 
//Output of id: 1492 

如果該鍵不存在:

var href = "http://www.example.org?id=1492"; 
var name = getURIParam(href, "name", "Unnamed"); 
//Output of name: Unnamed