your programing

URL 매개 변수 jquery 가져 오기 또는 js에서 쿼리 문자열 값을 가져 오는 방법

lovepro 2020. 10. 3. 11:23
반응형

URL 매개 변수 jquery 가져 오기 또는 js에서 쿼리 문자열 값을 가져 오는 방법


매개 변수 크기와 이름을 알 수없는 많은 jQuery 예제를 보았습니다. 내 URL에는 하나의 문자열 만있을 것입니다.

http://example.com?sent=yes

나는 단지 감지하고 싶다.

  1. 않는 sent존재 하는가?
  2. "예"와 같습니까?

여기에 최고의 솔루션 .

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
};

그리고 이것은 URL이라고 가정하고이 함수를 사용하는 방법
http://dummy.com/?technology=jquery&blog=jquerybyexample입니다.

var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');

2019 년 솔루션

우리는이 : http://example.com?sent=yes

let searchParams = new URLSearchParams(window.location.search)

합니까는 전송 존재를 ?

searchParams.has('sent') // true

그것이 동일 "예"에?

let param = searchParams.get('sent')

그런 다음 비교하십시오.


URL에 동적 변수를 매개 변수로 저장하고 스크립트와 함께 사용할 준비가 된 JavaScript 변수로 저장하는 jQuery 코드 스 니펫 :

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null) {
       return null;
    }
    return decodeURI(results[1]) || 0;
}

example.com?param1=name¶m2=&id=6

$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null

공백이있는 예제 매개 변수

http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));  
//output: Gold%20Coast



console.log(decodeURIComponent($.urlParam('city'))); 
//output: Gold Coast

나는 항상 이것을 한 줄로 붙입니다. 이제 params에는 vars가 있습니다.

params={};location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k]=v})

여러 줄 :

var params={};
window.location.search
  .replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
    params[key] = value;
  }
);

함수로서

function getSearchParams(k){
 var p={};
 location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
 return k?p[k]:p;
}

다음과 같이 사용할 수 있습니다.

getSearchParams()  //returns {key1:val1, key2:val2}

또는

getSearchParams("key1")  //returns val1

너무 늦었을 수 있습니다. 하지만이 방법은 아주 쉽고 간단합니다

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>

<!-- URL:  www.example.com/correct/?message=done&year=1990 -->

<script type="text/javascript">
$(function(){
    $.url.attr('protocol')  // --> Protocol: "http"
    $.url.attr('path')      // --> host: "www.example.com"
    $.url.attr('query')         // --> path: "/correct/"
    $.url.attr('message')       // --> query: "done"
    $.url.attr('year')      // --> query: "1990"
});

업데이트
는 url 플러그인이 필요합니다 : plugins.jquery.com/url
감사합니다 -Ripounet


또 다른 대체 기능 ...

function param(name) {
    return (location.search.split(name + '=')[1] || '').split('&')[0];
}

아니면이 깔끔한 작은 기능을 사용할 수 있습니다. 왜 솔루션이 너무 복잡할까요?

function getQueryParam(param) {
    location.search.substr(1)
        .split("&")
        .some(function(item) { // returns first occurence and stops
            return item.split("=")[0] == param && (param = item.split("=")[1])
        })
    return param
}

단순화하고 한 줄로 정리하면 더 좋아 보입니다.

tl; dr 단선 솔루션

var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
결과:
queryDict [ 'sent'] // 정의되지 않음 또는 '값'

하지만 인코딩 된 문자다중 값 키가 있다면 어떨까요?

이 대답을 더 잘 볼 수 있습니다. JavaScript에서 쿼리 문자열 값을 어떻게 얻을 수 있습니까?

맛보기

"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> queryDict
a: ["1", "5", "t e x t"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]

> queryDict["a"][1] // "5"
> queryDict.a[1] // "5"

사용 URLSearchParams:

var params = new window.URLSearchParams(window.location.search);
console.log(params.get('name'));

호환성에주의하세요 (대부분 괜찮지 만 IE와 Edge는 다른 이야기 일 수 있습니다. 호환 가능한 참조를 확인하려면 https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams )


아마 당신은 제공 할 수 있습니다 치과 JS에게 봐? (면책 조항 : 코드를 작성했습니다)

암호:

document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"

Dentist JS를 사용하면 기본적으로 모든 문자열 (예 : document.URL.extract ())에서 extract () 함수를 호출 할 수 있으며 발견 된 모든 매개 변수의 HashMap을 다시 얻을 수 있습니다. 구분 기호와 모든 것을 처리하도록 사용자 정의 할 수도 있습니다.

축소 된 버전 <1kb


이것은 간단하고 나를 위해 일했습니다.

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}

따라서 URL이 http://www.yoursite.com?city=4 인 경우

이 시도

console.log($.urlParam('city'));

이것이 도움이되기를 바랍니다.

 <script type="text/javascript">
   function getParameters() {
     var searchString = window.location.search.substring(1),
       params = searchString.split("&"),
       hash = {};

     if (searchString == "") return {};
     for (var i = 0; i < params.length; i++) {
       var val = params[i].split("=");
       hash[unescape(val[0])] = unescape(val[1]);
     }

     return hash;
   }

    $(window).load(function() {
      var param = getParameters();
      if (typeof param.sent !== "undefined") {
        // Do something.
      }
    });
</script>

function GetRequestParam(param)
{
	var res = null;
	try{
		var qs = decodeURIComponent(window.location.search.substring(1));//get everything after then '?' in URI
		var ar = qs.split('&');
		$.each(ar, function(a, b){
			var kv = b.split('=');
			if(param === kv[0]){
				res = kv[1];
				return false;//break loop
			}
		});
	}catch(e){}
	return res;
}


작업 데모 http://jsfiddle.net/xy7cX/를 사용해보십시오.

API :

이것은 도움이 될 것입니다 :)

암호

var url = "http://myurl.com?sent=yes"

var pieces = url.split("?");
alert(pieces[1] + " ===== " + $.inArray("sent=yes", pieces));

이 훌륭한 라이브러리가 있습니다 : https://github.com/allmarkedup/purl

간단하게 할 수 있습니다.

url = 'http://example.com?sent=yes';
sent = $.url(url).param('sent');
if (typeof sent != 'undefined') { // sent exists
   if (sent == 'yes') { // sent is equal to yes
     // ...
   }
}

예제는 jQuery를 사용하고 있다고 가정합니다. 일반 자바 스크립트처럼 사용할 수도 있습니다. 그러면 구문이 약간 달라집니다.


이것은 과잉 일 수 있지만 현재 URI.js 라는 URI 구문 분석에 사용할 수있는 꽤 인기있는 라이브러리가 있습니다 .

var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow";
var components = URI.parse(uri);
var query = URI.parseQuery(components['query']);
document.getElementById("result").innerHTML = "URI = " + uri;
document.getElementById("result").innerHTML += "<br>technology = " + query['technology'];

// If you look in your console, you will see that this library generates a JS array for multi-valued queries!
console.log(query['technology']);
console.log(query['blog']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script>

<span id="result"></span>


매우 간단하게 모든 URL을 사용하고 가치를 얻을 수 있습니다.

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

사용 예

// query string: ?first=value1&second=&value2
var foo = getParameterByName('first'); // "value1"
var bar = getParameterByName('second'); // "value2" 

참고 : 매개 변수가 여러 번 존재하는 경우 (? first = value1 & second = value2) 첫 번째 값 (value1)과 두 번째 값을 (value2)로 얻습니다.


이것은 당신에게 일하기 좋은 물건을 줄 것입니다

    function queryParameters () {
        var result = {};

        var params = window.location.search.split(/\?|\&/);

        params.forEach( function(it) {
            if (it) {
                var param = it.split("=");
                result[param[0]] = param[1];
            }
        });

        return result;
    }

그리고;

    if (queryParameters().sent === 'yes') { .....

이것은 Gazoris 의 답변을 기반으로 하지만 URL은 매개 변수를 디코딩하여 숫자와 문자 이외의 데이터를 포함 할 때 사용할 수 있습니다.

function urlParam(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    // Need to decode the URL parameters, including putting in a fix for the plus sign
    // https://stackoverflow.com/a/24417399
    return results ? decodeURIComponent(results[1].replace(/\+/g, '%20')) : null;
}

URI.js 라이브러리 를 사용하는 또 다른 예가 있습니다.

예제는 질문에 정확히 대답합니다.

var url = 'http://example.com?sent=yes';
var urlParams = new URI(url).search(true);
// 1. Does sent exist?
var sendExists = urlParams.sent !== undefined;
// 2. Is it equal to "yes"?
var sendIsEqualtToYes = urlParams.sent == 'yes';

// output results in readable form
// not required for production
if (sendExists) {
  console.log('Url has "sent" param, its value is "' + urlParams.sent + '"');
  if (urlParams.sent == 'yes') {
    console.log('"Sent" param is equal to "yes"');
  } else {
    console.log('"Sent" param is not equal to "yes"');
  }
} else {
  console.log('Url hasn\'t "sent" param');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script>


http://example.com?sent=yes

여기에 최고의 솔루션 .

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.href);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
};

위의 함수를 사용하면 개별 매개 변수 값을 얻을 수 있습니다.

getUrlParameter('sent');

Sameer의 답변의 Coffeescript 버전

getUrlParameter = (sParam) ->
  sPageURL = window.location.search.substring(1)
  sURLVariables = sPageURL.split('&')
  i = 0
  while i < sURLVariables.length
    sParameterName = sURLVariables[i].split('=')
    if sParameterName[0] == sParam
      return sParameterName[1]
    i++

Sameer의 답변에 약간의 개선, 호출 할 때마다 모든 매개 변수를 구문 분석하고 반복하는 것을 피하기 위해 매개 변수를 클로저로 캐시합니다.

var getURLParam = (function() {
    var paramStr = decodeURIComponent(window.location.search).substring(1);
    var paramSegs = paramStr.split('&');
    var params = [];
    for(var i = 0; i < paramSegs.length; i++) {
        var paramSeg = paramSegs[i].split('=');
        params[paramSeg[0]] = paramSeg[1];
    }
    console.log(params);
    return function(key) {
        return params[key];
    }
})();

나는 이것을 사용하고 작동합니다. http://codesheet.org/codesheet/NF246Tzs

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    vars[key] = value;
    });
return vars;
}


var first = getUrlVars()["id"];

With vanilla JavaScript, you could easily take the params (location.search), get the substring (without the ?) and turn it into an array, by splitting it by '&'.

As you iterate through urlParams, you could then split the string again with '=' and add it to the 'params' object as object[elmement[0]] = element[1]. Super simple and easy to access.

http://www.website.com/?error=userError&type=handwritten

            var urlParams = location.search.substring(1).split('&'),
                params = {};

            urlParams.forEach(function(el){
                var tmpArr = el.split('=');
                params[tmpArr[0]] = tmpArr[1];
            });


            var error = params['error'];
            var type = params['type'];

What if there is & in URL parameter like filename="p&g.html"&uid=66

In this case the 1st function will not work properly. So I modified the code

function getUrlParameter(sParam) {
    var sURLVariables = window.location.search.substring(1).split('&'), sParameterName, i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
}

Admittedly I'm adding my answer to an over-answered question, but this has the advantages of:

-- Not depending on any outside libraries, including jQuery

-- Not polluting global function namespace, by extending 'String'

-- Not creating any global data and doing unnecessary processing after match found

-- Handling encoding issues, and accepting (assuming) non-encoded parameter name

-- Avoiding explicit for loops

String.prototype.urlParamValue = function() {
    var desiredVal = null;
    var paramName = this.valueOf();
    window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
        var nameVal = currentValue.split('=');
        if ( decodeURIComponent(nameVal[0]) === paramName ) {
            desiredVal = decodeURIComponent(nameVal[1]);
            return true;
        }
        return false;
    });
    return desiredVal;
};

Then you'd use it as:

var paramVal = "paramName".urlParamValue() // null if no match

If you want to find a specific parameter from a specific url:

function findParam(url, param){
  var check = "" + param;
  if(url.search(check )>=0){
      return url.substring(url.search(check )).split('&')[0].split('=')[1];
  }
}  

var url = "http://www.yourdomain.com/example?id=1&order_no=114&invoice_no=254";  
alert(findParam(url,"order_no"));

Another solution that uses jQuery and JSON, so you can access the parameter values through an object.

var loc = window.location.href;
var param = {};
if(loc.indexOf('?') > -1)
{
    var params = loc.substr(loc.indexOf('?')+1, loc.length).split("&");

    var stringJson = "{";
    for(var i=0;i<params.length;i++)
    {
        var propVal = params[i].split("=");
        var paramName = propVal[0];
        var value = propVal[1];
        stringJson += "\""+paramName+"\": \""+value+"\"";
        if(i != params.length-1) stringJson += ",";
    }
    stringJson += "}";
    // parse string with jQuery parseJSON
    param = $.parseJSON(stringJson);
}

Assuming your URL is http://example.com/?search=hello+world&language=en&page=3

After that it's only a matter of using the parameters like this:

param.language

to return

en

The most useful usage of this is to run it at page load and make use of a global variable to use the parameters anywhere you might need them.

If your parameter contains numeric values then just parse the value.

parseInt(param.page)

If there are no parameters param will just be an empty object.


$.urlParam = function(name) {
  var results = new RegExp('[\?&amp;]' + name + '=([^&amp;#]*)').exec(window.location.href);
  return results[1] || 0;
}

use this

$.urlParam = function(name) {
  var results = new RegExp('[\?&amp;]' + name + '=([^&amp;#]*)').exec(window.location.href);
  return results[1] || 0;
}

참고URL : https://stackoverflow.com/questions/19491336/get-url-parameter-jquery-or-how-to-get-query-string-values-in-js

반응형