2015-04-29 45 views
9

我得到這個網址我驗證到谷歌如何從URL

http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600 

後,如何從這個網址access_token值獲得訪問令牌?

我試圖解決方案在下面的網址,他們都不工作

How can I get query string values in JavaScript?

在JS

How to get the value from the GET parameters?

Using the GET parameter of a URL in JavaScript

回答

5

我喜歡的正則表達式所以這裏是一個正則表達式的答案:

var url = 'http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600', 
    access_token = url.match(/\#(?:access_token)\=([\S\s]*?)\&/)[1]; 

access_token是:

ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw

(直接從控制檯)

Fiddle

+0

我也喜歡Regex!很好的答案 –

2

利用URL類:

var token = new URL("http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600").hash.split('&').filter(function(el) { if(el.match('access_token') !== null) return true; })[0].split('=')[1]; 
 

 
alert(token);

+1

似乎在末尾包含'&token_type' – Downgoat

+1

修正了它。添加了一點正則表達式香料和一些胡椒平滑過濾 –