JavaScript에서 URL의 get 매개 변수 사용 [Duplication
-
05-07-2019 - |
문제
이 질문은 이미 여기에 답이 있습니다.
내가 다음과 같은 페이지에있는 경우
http://somesite.com/somepage.php?param1=ASDF
해당 페이지의 JavaScript에서는 URL의 GET 부분에서 변수를 매개 변수 값으로 설정하고 싶습니다.
그래서 JavaScript에서 :
<script>
param1var = ... // ... would be replaced with the code to get asdf from URI
</script>
"..."는 무엇을할까요?
해결책
여기에 있습니다 샘플 코드 그에 대한.
<script>
var param1var = getQueryVariable("param1");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
</script>
다른 팁
위치 객체의 "검색"부분을 얻은 다음 구문 분석 할 수 있습니다.
var matches = /param1=([^&#=]*)/.exec(window.location.search);
var param1 = matches[1];
GNARF의 솔루션의 변형을 만들었으므로 호출과 결과는 PHP와 유사합니다.
function S_GET(id){
var a = new RegExp(id+"=([^&#=]*)");
return decodeURIComponent(a.exec(window.location.search)[1]);
}
그러나 함수에서 호출되는 것처럼 프로세스가 느려집니다. 글로벌로 사용하는 것이 좋습니다.
window['
var_name'] = decodeURIComponent( /
var_in_get=([^&#=]*)/.exec(window.location.search)[1] );
업데이트
여전히 JS를 배우면서 더 많은 JS 행동에서 더 나은 답변을 만들었습니다.
Url = {
get get(){
var vars= {};
if(window.location.search.length!==0)
window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
key=decodeURIComponent(key);
if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}
else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}
});
return vars;
}
};
이것은 단지 사용하기 만 할 수 있습니다 Url.get
.
예시URL ?param1=param1Value¶m2=param2Value
다음과 같이 호출 할 수 있습니다.
Url.get.param1 //"param1Value"
Url.get.param2 //"param2Value"
다음은 Snipet입니다.
// URL GET params
url = "?a=2&a=3&b=2&a=4";
Url = {
get get(){
var vars= {};
if(url.length!==0)
url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
key=decodeURIComponent(key);
if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}
else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}
});
return vars;
}
};
document.querySelector('log').innerHTML = JSON.stringify(Url.get);
<log></log>
내 프로그래밍 아카이브에서 :
function querystring(key) {
var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
var r=[], m;
while ((m=re.exec(document.location.search)) != null) r[r.length]=m[1];
return r;
}
값이 존재하지 않으면 빈 배열이 반환됩니다.
값이 존재하면 배열은 하나의 항목이있는 값인 반환입니다.
이름이있는 여러 값이 존재하면 각 값이 포함 된 배열이 반환됩니다.
예 :
var param1var = querystring("param1")[0];
document.write(querystring("name"));
if (querystring('id')=='42') alert('We apoligize for the inconvenience.');
if (querystring('button').length>0) alert(querystring('info'));
커피 스크립트로 수행 할 수있는 방법은 다음과 같습니다 (누군가가 관심이있는 경우).
decodeURIComponent( v.split( "=" )[1] ) if decodeURIComponent( v.split( "=" )[0] ) == name for v in window.location.search.substring( 1 ).split( "&" )
jQuery 사용? 나는 이것을 전에 사용했다 : http://projects.allmarkedup.com/jquery_url_parser/ 그리고 그것은 꽤 잘 작동했습니다.
이것은 괜찮아 보였다 :
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];
}
JSLINT가 좋아하는 버전은 다음과 같습니다.
/*jslint browser: true */
var GET = {};
(function (input) {
'use strict';
if (input.length > 1) {
var param = input.slice(1).replace(/\+/g, ' ').split('&'),
plength = param.length,
tmp,
p;
for (p = 0; p < plength; p += 1) {
tmp = param[p].split('=');
GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp[1]);
}
}
}(window.location.search));
window.alert(JSON.stringify(GET));
또는 EG와 같은 하나의 키에 대한 여러 값에 대한 지원이 필요한 경우. ? key = value1 & key = value2 당신은 이것을 사용할 수 있습니다.
/*jslint browser: true */
var GET = {};
(function (input) {
'use strict';
if (input.length > 1) {
var params = input.slice(1).replace(/\+/g, ' ').split('&'),
plength = params.length,
tmp,
key,
val,
obj,
p;
for (p = 0; p < plength; p += 1) {
tmp = params[p].split('=');
key = decodeURIComponent(tmp[0]);
val = decodeURIComponent(tmp[1]);
if (GET.hasOwnProperty(key)) {
obj = GET[key];
if (obj.constructor === Array) {
obj.push(val);
} else {
GET[key] = [obj, val];
}
} else {
GET[key] = val;
}
}
}
}(window.location.search));
window.alert(JSON.stringify(GET));
이 기능을 사용할 수 있습니다
function getParmFromUrl(url, parm) {
var re = new RegExp(".*[?&]" + parm + "=([^&]+)(&|$)");
var match = url.match(re);
return(match ? match[1] : "");
}
이미 PHP 페이지를 실행하고 있다면
PHP 비트 :
$json = json_encode($_REQUEST, JSON_FORCE_OBJECT);
print "<script>var getVars = $json;</script>";
JS 비트 :
var param1var = getVars.param1var;
그러나 HTML 페이지의 경우 Jose Basilio의 솔루션은 나에게 좋아 보인다.
행운을 빕니다!
실제로 특별한 일을 할 필요는 없습니다. JavaScript와 PHP를 함께 혼합하여 PHP에서 JavaScript로 변수를 얻을 수 있습니다.
var param1val = '<?php echo $_GET['param1'] ?>';