programing

자바스크립트 / jQuery에서 $.param( ) 역함수

easyjava 2023. 10. 1. 23:08
반응형

자바스크립트 / jQuery에서 $.param( ) 역함수

다음과 같은 양식이 주어집니다.

<form>
    <input name="foo" value="bar">
    <input name="hello" value="hello world">
</form>

나는 사용할 수 있습니다.$.param( .. )양식을 직렬화하도록 구성합니다.

$.param( $('form input') )

=> foo=bar&hello=hello+world

자바스크립트로 위 문자열을 역직렬화하고 해시백을 받으려면 어떻게 해야 합니까?

예를들면,

$.magicFunction("foo=bar&hello=hello+world")

=> {'foo' : 'bar', 'hello' : 'hello world'}

참조: .

jQuery BBQdeparam 기능을 사용하셔야 합니다.테스트가 잘 되어 있고 문서화되어 있습니다.

이것은 제가 얼마 전에 비슷한 작업을 하기 위해 작성한 함수를 약간 수정한 것입니다.

var QueryStringToHash = function QueryStringToHash  (query) {
  var query_string = {};
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    pair[0] = decodeURIComponent(pair[0]);
    pair[1] = decodeURIComponent(pair[1]);
        // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = pair[1];
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]], pair[1] ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(pair[1]);
    }
  } 
  return query_string;
};

이 짧은 기능적 접근 방식은 어떻습니까?

function parseParams(str) {
    return str.split('&').reduce(function (params, param) {
        var paramSplit = param.split('=').map(function (value) {
            return decodeURIComponent(value.replace(/\+/g, ' '));
        });
        params[paramSplit[0]] = paramSplit[1];
        return params;
    }, {});
}

예:

parseParams("this=is&just=an&example") // Object {this: "is", just: "an", example: undefined}

내 대답:

function(query){
  var setValue = function(root, path, value){
    if(path.length > 1){
      var dir = path.shift();
      if( typeof root[dir] == 'undefined' ){
        root[dir] = path[0] == '' ? [] : {};
      }

      arguments.callee(root[dir], path, value);
    }else{
      if( root instanceof Array ){
        root.push(value);
      }else{
        root[path] = value;
      }
    }
  };
  var nvp = query.split('&');
  var data = {};
  for( var i = 0 ; i < nvp.length ; i++ ){
    var pair = nvp[i].split('=');
    var name = decodeURIComponent(pair[0]);
    var value = decodeURIComponent(pair[1]);

    var path = name.match(/(^[^\[]+)(\[.*\]$)?/);
    var first = path[1];
    if(path[2]){
      //case of 'array[level1]' || 'array[level1][level2]'
      path = path[2].match(/(?=\[(.*)\]$)/)[1].split('][')
    }else{
      //case of 'name'
      path = [];
    }
    path.unshift(first);

    setValue(data, path, value);
  }
  return data;
}

저는 데이비드 도워드의 답변을 사용하고 있는데, 그것이 PHP나 Rails의 Ruby와는 다르게 작동한다는 것을 깨달았습니다.

1) 입니다로 입니다.[]를 들면,?choice[]=1&choice[]=12, 그럴 때는 그렇지 않습니다?a=1&a=2

여러 개의 서버에서와 온 (2) , PHP 는합니다(루비 온 레일스 합니다).?a=1&b=2&a=3

그래서 데이빗 버전을 수정하면 다음과 같은 것이 있습니다.

function QueryStringToHash(query) {

  if (query == '') return null;

  var hash = {};

  var vars = query.split("&");

  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    var k = decodeURIComponent(pair[0]);
    var v = decodeURIComponent(pair[1]);

    // If it is the first entry with this name
    if (typeof hash[k] === "undefined") {

      if (k.substr(k.length-2) != '[]')  // not end with []. cannot use negative index as IE doesn't understand it
        hash[k] = v;
      else
        hash[k.substr(0, k.length-2)] = [v];

    // If subsequent entry with this name and not array
    } else if (typeof hash[k] === "string") {
      hash[k] = v;  // replace it

    // If subsequent entry with this name and is array
    } else {
      hash[k.substr(0, k.length-2)].push(v);
    }
  } 
  return hash;
};

꽤나 철저하게 테스트를 해본 적잖습니까

이것이 오래된 실이라는 것은 알지만, 아직도 관련성이 있는 것은 아닐까요?

Jacky Li의 좋은 솔루션에 영감을 받아 배열과 객체의 임의 조합도 입력으로 처리할 수 있도록 목표를 가지고 자신만의 약간의 변형을 시도했습니다.저는 PHP가 어떻게 했을지 살펴보고 "유사한" 일을 하려고 노력했습니다.여기 내 코드가 있습니다.

function getargs(str){
   var ret={};
   function build(urlnam,urlval,obj){ // extend the return object ...
    var i,k,o=obj, x, rx=/\[([^\]]*)\]/g, idx=[urlnam.replace(rx,'')];
    while (x=rx.exec(urlnam)) idx.push(x[1]); 
    while(true){
     k=idx.shift();
     if(k.trim()=='') {// key is empty: autoincremented index
       if (o.constructor.name=='Array') k=o.length; // for Array
       else if (o===obj ) {k=null}  // for first level property name
       else {k=-1;                                  // for Object
         for(i in o) if (+i>k) k=+i;
         k++;
       }
     }
     if(idx.length) { 
       // set up an array if the next key (idx[0]) appears to be
       // numeric or empty, otherwise set up an object:
       if (o[k]==null || typeof o[k]!='object') o[k]=isNaN(idx[0])?{}:[]; 
       o=o[k]; // move on to the next level
     }
     else { // OK, time to store the urlval in its chosen place ...
       // console.log('key',k,'val',urlval);                 
       o[k]=urlval===""?null:urlval; break; // ... and leave the while loop.
     } 
    }
    return obj;
   }
   // ncnvt: is a flag that governs the conversion of
   // numeric strings into numbers
   var ncnvt=true,i,k,p,v,argarr=[],
       ar=(str||window.location.search.substring(1)).split("&"),
       l=ar.length;
   for (i=0;i<l;i++) {if (ar[i]==="") continue;
     p=ar[i].split("=");k=decodeURIComponent(p[0]);
     v=p[1];v=(v!=null)?decodeURIComponent(v.replace(/\+/g,'%20')):'';
     if (ncnvt && v.trim()>"" && !isNaN(v)) v-=0;
     argarr.push([k,v]);  // array: key-value-pairs of all arguments
   }
   for (i=0,l=argarr.length;i<l;i++) build(argarr[i][0],argarr[i][1],ret);
   return ret;
}

가 없이 str- - 입니다입니다window.location.search.slice(1)

몇 가지 예:

['a=1&a=2',                               // 1
 'x[y][0][z][]=1',                        // 2
 'hello=[%22world%22]&world=hello',       // 3
 'a=1&a=2&&b&c=3&d=&=e&',                 // 4
 'fld[2][]=2&fld[][]=3&fld[3][]=4&fld[]=bb&fld[]=cc',  // 5
 $.param({a:[[1,2],[3,4],{aa:'one',bb:'two'},[5,6]]}), // 6
 'a[]=hi&a[]=2&a[3][]=7&a[3][]=99&a[]=13',// 7
 'a[x]=hi&a[]=2&a[3][]=7&a[3][]=99&a[]=13'// 8
].map(function(v){return JSON.stringify(getargs(v));}).join('\n')

결과를 보다

{"a":2}                                    // 1
{"x":{"y":[{"z":[1]}]}}                    // 2
{"hello":"[\"world\"]","world":"hello"}    // 3
{"a":2,"b":null,"c":3,"d":null,"null":"e"} // 4 = { a: 2, b: null, c: 3, d: null, null: "e" }
{"fld":[null,null,[2],[3,4],"bb","cc"]}    // 5 
{"a":[[1,2],[3,4],{"aa":"one","bb":"two"},[5,6]]}  // 6
{"a":["hi",2,null,[7,99],13]}              // 7
{"a":{"0":2,"3":[7,99],"4":13,"x":"hi"}}   // 8

은 입니다를 입니다.a

{a:{"0":["1","2"],"1":["3","4"],"2":["5","6"]}} // 6: JackyLi's output

getargs()는 임의의 레벨에 대한 첫 번째 주어진 인덱스를 보고 이 레벨이 개체(numeric 인덱스가 아닌)가 될지 배열(numeric 또는 비어 있는지) 중 어느 것이 될지를 결정합니다. 따라서 위의 목록(6번)과 같이 출력이 됩니다.

nulls는 빈 자리를 나타내기 위해 필요한 곳에 삽입됩니다.배열은 항상 연속적으로 번호가 매겨지고 0을 기준으로 합니다.

예제 no. 8에서는 배열이 아닌 객체를 다루고 있음에도 불구하고 빈 인덱스에 대한 "자동 증가"가 여전히 작동합니다.

해 본 내 .getargs()한 jQuery다와 합니다.$.deparam() 승인된 답변에 언급된 플러그인.가장 큰 차이점은getargsjQuery를 사용하지 않고 실행되며 개체에서 자동 증분을 수행됩니다.$.deparam()그렇게 하지 않을 것입니다.

JSON.stringify($.deparam('a[x]=hi&a[]=2&a[3][]=7&a[3][]=99&a[]=13').a);

결과를 보다

{"3":["7","99"],"x":"hi","undefined":"13"}

$.deparam()x[]됩니다.undefined자동 증가 수치 지수 대신에.

새 jQuery 함수를 만드는 방법은 다음과 같습니다.

jQuery.unparam = function (value) {
    var
    // Object that holds names => values.
    params = {},
    // Get query string pieces (separated by &)
    pieces = value.split('&'),
    // Temporary variables used in loop.
    pair, i, l;

    // Loop through query string pieces and assign params.
    for (i = 0, l = pieces.length; i < l; i++) {
        pair = pieces[i].split('=', 2);
        // Repeated parameters with the same name are overwritten. Parameters
        // with no value get set to boolean true.
        params[decodeURIComponent(pair[0])] = (pair.length == 2 ?
            decodeURIComponent(pair[1].replace(/\+/g, ' ')) : true);
    }

    return params;
};

그 덕분에 http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

꽤 쉬운 :D

function params_unserialize(p){
var ret = {},
    seg = p.replace(/^\?/,'').split('&'),
    len = seg.length, i = 0, s;
for (;i<len;i++) {
    if (!seg[i]) { continue; }
    s = seg[i].split('=');
    ret[s[0]] = s[1];
}
return ret;}

이것은 정말 오래된 질문이지만, 내가 오면서 - 다른 사람들이 이 게시물에 올 수 있고, 나는 이 주제를 약간 새로고침하고 싶습니다.현재는 맞춤형 솔루션을 만들 필요가 없습니다. URL 검색 파라미터 인터페이스가 있습니다.

var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);

//Iterate the search parameters.
for (let p of searchParams) {
  console.log(p);
}

제가 아는 유일한 제한 사항은 IE/Edge에서 지원되지 않는 기능입니다.

서버측 JScript ASP Classic 페이지(데모)에서 사용하는 JavaScript 구현은 다음과 같습니다.

// Transforms a query string in the form x[y][0][z][]=1 into {x:{y:[{z:[1]}]}}
function parseJQueryParams(p) {
    var params = {};
    var pairs = p.split('&');
    for (var i=0; i<pairs.length; i++) {
        var pair = pairs[i].split('=');
        var indices = [];
        var name = decodeURIComponent(pair[0]),
            value = decodeURIComponent(pair[1]);

        var name = name.replace(/\[([^\]]*)\]/g, 
            function(k, idx) { indices.push(idx); return ""; });

        indices.unshift(name);
        var o = params;

        for (var j=0; j<indices.length-1; j++) {
            var idx = indices[j];
            var nextIdx = indices[j+1];
            if (!o[idx]) {
                if ((nextIdx == "") || (/^[0-9]+$/.test(nextIdx)))
                    o[idx] = [];
                else
                    o[idx] = {};
            }
            o = o[idx];
        }

        idx = indices[indices.length-1];
        if (idx == "") {
            o.push(value);
        }
        else {
            o[idx] = value;
        }
    }
    return params;
}

저는 이와 같은 해결책을 생각해 냈습니다. HttpUtility.ParseQueryString.

변수는 에 저장되므로 과 같습니다qsObj["param"]입니다에 하는 것과 .GetValues("param")순 에서.

마음에 드셨으면 좋겠습니다.JQuery가 필요하지 않습니다.

var parseQueryString = function (querystring) {
    var qsObj = new Object();
    if (querystring) {
        var parts = querystring.replace(/\?/, "").split("&");
        var up = function (k, v) {
            var a = qsObj[k];
            if (typeof a == "undefined") {
                qsObj[k] = [v];
            }
            else if (a instanceof Array) {
                a.push(v);
            }
        };
        for (var i in parts) {
            var part = parts[i];
            var kv = part.split('=');
            if (kv.length == 1) {
                var v = decodeURIComponent(kv[0] || "");
                up(null, v);
            }
            else if (kv.length > 1) {
                var k = decodeURIComponent(kv[0] || "");
                var v = decodeURIComponent(kv[1] || "");
                up(k, v);
            }
        }
    }
    return qsObj;
};

사용 방법은 다음과 같습니다.

var qsObj = parseQueryString("a=1&a=2&&b&c=3&d=&=e&");

콘솔 juste에서 결과를 미리 보려면 다음을 입력합니다.

JSON.stringify(qsObj)

출력:

"{"a":["1","2"],"null":["","b",""],"c":["3"],"d":[""],"":["e"]}"

CSS-Tricks(Nicholas Ortenzio의 원본 자료)에 멋진 한 줄이 있습니다.

function getQueryParameters(str) {
    return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
}

의 입니다를 사용하느냐 하는 입니다.this문자열의 각 쿼리에 대한 키/값 쌍을 추가하는 개체입니다.그렇기는 하지만 개선의 여지가 있습니다.아래와 같이 조금 수정했는데 다음과 같이 변경되었습니다.

  1. 빈 문자열 및 문자열이 아닌 입력의 처리가 추가되었습니다.

  2. 된 URI 된 URI ()%40->@),).

  3. 했습니다의 기본 했습니다.document.location.search입력이 비어 있을 때.

  4. 이름을 바꾸고, 읽기 쉽게 만들고, 의견을 추가했습니다.

function deparam(str) {
    // Uses an empty 'this' to build up the results internally
    function splitQuery(query) {
        query = query.split('=').map(decodeURIComponent);
        this[query[0]] = query[1];
        return this;
    }

    // Catch bad input
    if (!str || !(typeof str === 'string' || str instanceof String))
        return {};

    // Split the string, run splitQuery on each piece, and return 'this'
    var queries = str.replace(/(^\?)/,'').split('&');
    return queries.map(splitQuery.bind({}))[0];
}

사용 방법:

// convert query string to json object
var queryString = "cat=3&sort=1&page=1";

queryString
    .split("&")
    .forEach((item) => {
        const prop = item.split("=");
        filter[prop[0]] = prop[1];
    });

console.log(queryString);

이건 커피 대본에 있는 제 버전입니다.url합니다와 합니다.http://localhost:4567/index.html?hello=[%22world%22]&world=hello#/home

getQueryString: (url)->
    return null if typeof url isnt 'string' or url.indexOf("http") is -1

    split = url.split "?"

    return null if split.length < 2 
    path = split[1]

    hash_pos = path.indexOf "#"
    path = path[0...hash_pos] if hash_pos isnt -1

    data = path.split "&"
    ret = {}
    for d in data
      [name, val] = d.split "=" 
      name = decodeURIComponent name
      val = decodeURIComponent val
      try 
        ret[name] = JSON.parse val
      catch error
        ret[name] = val
    return ret

GET 요청에서 파라미터를 신속하게 가져오려면 다음과 같이 간단하고 압축적인 방법을 제공합니다.

function httpGet() {
    var a={},b,i,q=location.search.replace(/^\?/,"").split(/\&/);
    for(i in q) if(q[i]) {b=q[i].split("=");if(b[0]) a[b[0]]=
    decodeURIComponent(b[1]).replace(/\+/g," ");} return a;
}

변환합니다.

something?aa=1&bb=2&cc=3

와 같은 대상으로

{aa:1,bb:2,cc:3}

배열 또는 개체의 직렬화된 표현을 만듭니다(AJAX 요청의 URL 쿼리 문자열로 사용할 수 있음).

<button id='param'>GET</button> 
<div id="show"></div>
<script>
  $('#param').click(function () {
    var personObj = new Object();
    personObj.firstname = "vishal"
    personObj.lastname = "pambhar";
    document.getElementById('show').innerHTML=$.param(`personObj`));
  });
</script>
output:firstname=vishal&lastname=pambhar

답변은 약간의 jQuery 우아함을 사용할 수 있습니다.

(function($) {
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
    var params = {}, e;
    while ( e = re.exec(query) ) {
        var k = decode( e[1] ), v = decode( e[2] );
        if (k.substring(k.length - 2) === '[]') {
            k = k.substring(0, k.length - 2);
            (params[k] || (params[k] = [])).push(v);
        }
        else params[k] = v;
    }
    return params;
};
})(jQuery);

https://gist.github.com/956897 에 접속합니다.

그 기능을 사용하시면 됩니다..serializeArray()jQuery 자체의 (Link).이 함수는 키-값 쌍의 배열을 반환합니다.결과 예:

[
  { name: "id", value: "1" },
  { name: "version", value: "100" }
]

언급URL : https://stackoverflow.com/questions/1131630/the-param-inverse-function-in-javascript-jquery

반응형