开发者

Encode client request params in Node.js

I need a method/implementation in Node.js that get a hash or array, and transform it to the HTML request param, just like jQuery.param()

var myObject = {
  a: {
    one: 1, 
    two: 2, 
    three: 3
  }, 
  b: [1,2,3]
}; // => "a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3"

*I just cant use it from jQuery since it depends on 开发者_如何学JAVABrowser native implementations.


I don't know such native function or module but you can use this one:

// Query String able to use escaping
var query = require('querystring');

function toURL(object, prefix)
{
  var result = '',
    key = '',
    postfix = '&';

  for (var i in object)
  {
    // If not prefix like a[one]...
    if ( ! prefix)
    {
      key = query.escape(i);
    }
    else
    {
      key = prefix + '[' + query.escape(i) + ']';
    }

    // String pass as is...
    if (typeof(object[i]) == 'string')
    {
      result += key + '=' + query.escape(object[i]) + postfix;
      continue;
    }

    // objectects and arrays pass depper
    if (typeof(object[i]) == 'object' || typeof(object[i]) == 'array')
    {
      result += toURL(object[i], key) + postfix;
      continue;
    }

    // Other passed stringified
    if (object[i].toString)
    {
      result += key + '=' + query.escape(object[i].toString()) + postfix;
      continue;
    }
  }
  // Delete trailing delimiter (&) Yep it's pretty durty way but
  // there was an error gettin length of the objectect;
  result = result.substr(0, result.length - 1);
  return result;
}

// try
var x = {foo: {a:{xxx:9000},b:2}, '[ba]z': 'bob&jhonny'};
console.log(toURL(x));
// foo[a]=1&foo[b]=2&baz=bob%26jhonny
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜