在Node.js中编码客户端请求参数

时间:2011-08-11 17:14:32

标签: http encoding node.js

需要Node.js 中的方法/实现来获取哈希或数组,并将其转换为HTML请求参数,就像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"

*我只是不能从jQuery中使用它,因为它依赖于浏览器原生实现。

1 个答案:

答案 0 :(得分:2)

我不知道这样的原生函数或模块,但你可以使用这个:

// 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