2011-05-17 37 views
5

我有一個搜索功能,並希望在搜索輸入中顯示搜索詞。從URL中提取詞

我的網址是:search-1.html?keyword=XXXXXX

我如何獲得這一點,並在輸入顯示呢?

預先感謝您。

回答

2

如果它僅僅是一個key=value url中你可以這樣使用簡單的正則表達式:

var theValueYouWant = window.location.href.match(/keyword=(.+)/)[1] 

然後設置這樣的輸入的值

$('input').val(theValueYouWant) 

如果你想更徹底解析GET字符串,這個功能應該做...

gets = {}; 
$.each(location.search.replace(/^\?/,'').split('&'),function(k,v){ 
    bits = v.split('='); 
    gets[bits[0]] = bits[1]; 
}); 
3

使用此: http://ajaxcssblog.com/jquery/url-read-get-variables/

走好運!

哦,那麼你可以使用下面的輸入字段中顯示它的值:

$("#inputId").val($.url.param("keyword")); 
+0

漂亮和微小的插件+1 – Pinkie 2011-05-17 21:49:01

+0

是的,我喜歡它。我把它加載到我的大部分網站當中是一種習慣,因爲它已經(快速,簡單地)訪問JS中的GET變量是多麼有用。 – Todd 2011-05-17 21:55:53

0

的jQuery少的解決方案:

<script type="text/javascript"> 
var $_GET=[],pairs=location.href.toString().substring(location.href.toString().indexOf("?")+1).split("&");for(key in pairs){pos=pairs[key].indexOf("=");$_GET[pairs[key].substring(0,pos)]=decodeURIComponent(pairs[key].substring(pos+1).replace(/\+/g," "))}; 

// Now just access with $_GET 
// example... 
keyword = $_GET["keyword"]; 
</script> 
1

正則表達式的解決方案:

var S = window.location.search; // "?keyword=..." etc. 
var T = S.match(/^\?(?:[^\b]*&+)?keyword=([^&]*)/); 
if (T) 
    T = T[1] 
else 
    T = "no keywords found" 

如果多個值均爲「關鍵字「(前?keyword=XXX&keyword=YYY),正則表達式只會找到這些值中的第一個(e.x. XXX)。即使查詢字符串中有其他變量,該正則表達式也可以工作。

+0

你確定這個工作。嘗試http://jsfiddle.net/pLHGh?hi=1&hi2=2 – Pinkie 2011-05-17 21:47:04

+0

@pinkie,這是因爲jsfiddle中的腳本在'iframe'中運行。如果你使用http://fiddle.jshell.net/pLHGh/show/light/?hi=1&hi2=2的'iframe' url,它可以工作。 – 2011-05-17 21:57:57

+0

@gaby是的你是對的。好的解決方案 – Pinkie 2011-05-17 22:00:12