program story

JQuery로 GET 및 POST 변수를 얻는 방법?

inputbox 2020. 8. 28. 07:25
반응형

JQuery로 GET 및 POST 변수를 얻는 방법?


어떻게 간단하게받을 수 있나요 GETPOSTJQuery와 함께 값?

내가 원하는 것은 다음과 같습니다.

$('#container-1 > ul').tabs().tabs('select', $_GET('selectedTabIndex'));

GET 매개 변수의 경우 다음에서 가져올 수 있습니다 document.location.search.

var $_GET = {};

document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
    }

    $_GET[decode(arguments[1])] = decode(arguments[2]);
});

document.write($_GET["test"]);

POST 매개 변수의 경우 $_POSTJSON 형식 객체를 <script>태그 직렬화 할 수 있습니다 .

<script type="text/javascript">
var $_POST = <?php echo json_encode($_POST); ?>;

document.write($_POST["test"]);
</script>

서버 측에서 작업하는 동안 PHP에서도 GET 매개 변수를 수집 할 수 있습니다.

var $_GET = <?php echo json_encode($_GET); ?>;

참고 : 내장 json_encode기능 을 사용하려면 PHP 버전 5 이상이 필요 합니다.


업데이트 : 다음은보다 일반적인 구현입니다.

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

var $_GET = getQueryParams(document.location.search);

.getUrlParams 라는 GET 매개 변수를 가져 오는 jQuery 용 플러그인이 있습니다.

POST의 경우 유일한 해결책은 Moran이 제안한 것처럼 PHP를 사용하여 POST를 자바 스크립트 변수로 에코하는 것입니다.


좋은 오래된 PHP를 사용하지 않는 이유는 무엇입니까? 예를 들어 GET 매개 변수 'target'을 받았다고 가정 해 보겠습니다.

function getTarget() {
    var targetParam = "<?php  echo $_GET['target'];  ?>";
    //alert(targetParam);
}

또는 http://plugins.jquery.com/project/parseQuery를 사용할 수 있습니다. 대부분의 것보다 작고 (최소 449 바이트) 이름-값 쌍을 나타내는 객체를 반환합니다.


서버 측 언어를 사용하면 POST 변수를 javascript로 내 보내야합니다.

.그물

var my_post_variable = '<%= Request("post_variable") %>';

빈 값에주의하십시오. 내보내려는 변수가 실제로 비어 있으면 자바 스크립트 구문 오류가 발생합니다. 문자열이라는 것을 알고 있다면 따옴표로 묶어야합니다. 정수인 경우 javascript에 줄을 쓰기 전에 실제로 존재하는지 테스트 할 수 있습니다.


jQuery 용 Query String Object 플러그인을 사용해 볼 수 있습니다 .


Here's something to gather all the GET variables in a global object, a routine optimized over several years. Since the rise of jQuery, it now seems appropriate to store them in jQuery itself, am checking with John on a potential core implementation.

jQuery.extend({
    'Q' : window.location.search.length <= 1 ? {}
        : function(a){
            var i = a.length, 
                r = /%25/g,  // Ensure '%' is properly represented 
                h = {};      // (Safari auto-encodes '%', Firefox 1.5 does not)
            while(i--) {
                var p = a[i].split('=');
                h[ p[0] ] = r.test( p[1] ) ? decodeURIComponent( p[1] ) : p[1];
            }
            return h;
        }(window.location.search.substr(1).split('&'))
});

Example usage:

switch ($.Q.event) {
    case 'new' :
        // http://www.site.com/?event=new
        $('#NewItemButton').trigger('click');
        break;
    default :
}

Hope this helps. ;)


jQuery plugins seem nice but what I needed is a quick js function to parse the get params. Here is what I have found.

http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx


If your $_GET is multidimensional, this might be what you're wanting:

var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
            return decodeURIComponent(s.split("+").join(" "));
    }

    //handling for multidimensional arrays
    if(decode(arguments[1]).indexOf("[]") > 0){
        var newName = decode(arguments[1]).substring(0, decode(arguments[1]).length - 2);
        if(typeof $_GET[newName] == 'undefined'){
            $_GET[newName] = new Array();
        }
        $_GET[newName].push(decode(arguments[2]));
    }else{
        $_GET[decode(arguments[1])] = decode(arguments[2]);
    }
});

simple, but yet usefull to get vars/values from URL:

function getUrlVars() {
    var vars = [], hash, hashes = null;
    if (window.location.href.indexOf("?") && window.location.href.indexOf("&")) {
        hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    } else if (window.location.href.indexOf("?")) {
        hashes = window.location.href.slice(window.location.href.indexOf('?') + 1);
    }
    if (hashes != null) {
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1];
        }
    }
    return vars;
}

I found it somewhere on the internet, just fixed few bugs


Use following function:

var splitUrl = function() {
    var vars = [], hash;
    var url = document.URL.split('?')[0];
    var p = document.URL.split('?')[1];
    if(p != undefined){
        p = p.split('&');
        for(var i = 0; i < p.length; i++){
            hash = p[i].split('=');
            vars.push(hash[1]);
            vars[hash[0]] = hash[1];
        }
    }
    vars['url'] = url;
    return vars;
};

and access variables as vars['index'] where 'index' is name of the get variable.


Just for the record, I wanted to know the answer to this question, so I used a PHP method:

<script>
var jGets = new Array ();
<?
if(isset($_GET)) {
    foreach($_GET as $key => $val)
        echo "jGets[\"$key\"]=\"$val\";\n";
}
?>
</script>

That way all my javascript/jquery that runs after this can access everything in the jGets. Its an nice elegant solution I feel.


My approach:

var urlParams;
(window.onpopstate = function () {
var match,
      pl     = /\+/g,  Regex for replacing addition symbol with a space
       search = /([^&=]+)=?([^&]*)/g,
      decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
       query  = window.location.search.substring(1);
   urlParams = {};
   while (match = search.exec(query))
    urlParams[decode(match[1])] = decode(match[2]);
})();

Keep it simple

replace VARIABLE_KEY with the key of the variable to get its value

 var get_value = window.location.href.match(/(?<=VARIABLE_KEY=)(.*?)[^&]+/)[0]; 

참고URL : https://stackoverflow.com/questions/439463/how-to-get-get-and-post-variables-with-jquery

반응형