Convert JavaScript object into URI-encoded string

后端 未结 11 1365
庸人自扰
庸人自扰 2020-12-04 18:54

I got a JavaScript object which I would like to get x-www-form-urlencoded.

Something like $(\'#myform\').serialize() but for objects.

相关标签:
11条回答
  • 2020-12-04 19:45

    You need to use JSON.stringify() to serialize the JSON/JavaScript object.

    It is natively available in almost all the modern browsers but you can include the below js which will add the required library incase it is not available.

    http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js

    0 讨论(0)
  • 2020-12-04 19:46

    Since you were asking for a serialized object, this is probably slightly off the mark. But just in case, if your intent is to use the values within that object as individual parameters, this might be the conversion you're looking for:

    var params = {
        "param1": "arg1",
        "param2": "arg2"
    };
    var query = "";
    for (key in params) {
        query += encodeURIComponent(key)+"="+encodeURIComponent(params[key])+"&";
    }
    xmlhttp.send(query);
    
    0 讨论(0)
  • 2020-12-04 19:47

    Same as above in effect, but functional style gives an elegant expression::

    const to_encoded = obj => Object.keys(obj).map(k =>
        `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&');
    
    0 讨论(0)
  • 2020-12-04 19:51

    To build on @Claymore's answer, Here is a function to encode an object and additionally omit the trailing ampersand:

    encodeObject(params) {
      var query = [];
      for (let key in params) {
        let val = encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
        query.push(val);
      }
      return query.join('&');
    }
    
    0 讨论(0)
  • 2020-12-04 19:53
    function jsonToURI(jsonObj) {
        var output = '';
        var keys = Object.keys(jsonObj);
        keys.forEach(function(key) {
            output = output + key + '=' + jsonObj[key] + '&';
        })
        return output.slice(0, -1);
    }
    
    function uriToJSON(urijson) {
        var output = {};
        urijson = decodeURIComponent(urijson);
        urijson = urijson.split('&');
        urijson.forEach(function(param) {
            var param = param.split('=');
            output[param[0]] = param[1];
        })
        return output
    }
    
    0 讨论(0)
提交回复
热议问题