2014-07-06 2 views
0

자바 스크립트를 사용하여 URL에서 'code'매개 변수를 추출하려고합니다.자바 스크립트를 사용하여 URL 검색어 문자열을 추출하는 중

아무도 내가 아래에 쓴 자바 스크립트가 HTML 페이지에서 쿼리 문자열을 인쇄하지 않는 이유를 말해 줄 수 있습니까?

귀하의 도움에 감사드립니다.

URL : google.com?code=123456789

HTML 코드 :

<html> 
<body> 

Your code is: 
<script> 
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 code = getUrlVars()["code"]; 
} 
</script> 

</body> 
</html> 
+0

당신은 함수 선언의 외부 함수 호출을 이동해야합니다. 우선 첫째로. –

답변

0
function getUrlVars() { 
    var vars = {}, //you need object aka hash not an array 
     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('='); 
     //you need to decode uri components 
     vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]); 
    } 
    return vars; 

} 

//you need to call the function outside of its declaration 
var code = getUrlVars()["code"]; 
document.write(code); //immediate write to document 
or: console.log(code); //log to console 
관련 문제