How to implement something like PHP's http_build_query and the reverse in javascript?

后端 未结 3 1012
离开以前
离开以前 2021-02-15 11:24
\'bar\',
              \'baz\'=>\'boom\',
              \'cow\'=>\'milk\',
              \'php\'=>\'hypertext processor\');

         


        
3条回答
  •  孤城傲影
    2021-02-15 12:03

    You can use the URLSearchParams class:

    var searchParametersData = {
      "foo": "baz",
      "bar": "foo"
    };
    
    var searchParameters = new URLSearchParams();
    
    Object.keys(searchParametersData).forEach(function(parameterName) {
      searchParameters.append(parameterName, searchParametersData[parameterName]);
    });
    
    console.log(searchParameters.toString()); // foo=baz&bar=foo
    

    To get the parameters object from a search parameter string, use this:

    var searchParametersString = "foo=baz&bar=foo";
    
    var searchParameters = new URLSearchParams(searchParametersString);
    
    var searchParametersData = {};
    
    for (var searchParameter of searchParameters) {
      searchParametersData[searchParameter[0]] = searchParameter[1];
    }
    
    console.log(searchParametersData); // {foo: "baz", bar: "foo"}
    

提交回复
热议问题