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

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

         


        
相关标签:
3条回答
  • 2021-02-15 12:01

    If you're using jQuery, then you can use the jQuery.param() function:

    var obj = { "foo":"bar", "baz":"boom", "php":"hypertext processor" };
    var str = jQuery.param(obj);
    alert(str); // should be "foo=bar&baz=boom&php=hypertext+processor"
    

    It can serialise some complex arrays too.

    0 讨论(0)
  • 2021-02-15 12:01

    Try the jQuery query plugin. It's pretty intuitive. You can use get and set accessors to read and modify the query string:

    var cow = $.query.get('cow');
    $.query.set('cow', 'goat');
    

    You can create a new query object from an existing string:

    var fromVar = $.query.load('?cow=milk')
    var cow = fromVar.get('cow'); // milk
    

    You can also create an empty object:

    var newQ = $.query.empty();
    newQ = newQ.set('first', 'value'); // "?first=value"
    
    0 讨论(0)
  • 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"}
    
    0 讨论(0)
提交回复
热议问题