2011-08-11 89 views
0

需要的Node.js那得到一個哈希或數組的方法/實現,並將其轉化到HTML請求PARAM,就像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中使用它,因爲它依賴於瀏覽器本地實現。

回答

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 
+0

有,你寫了一個錯誤:'的typeof(對象[1])==「objectect'',應該是''object''做遞歸 –

+1

另外,請注意這個例子失敗:'var x = {foo:{a:{xxx:9000},b:2},baz:'bob&jhonny'};'due雙重編碼 –

+0

Bug修復:)最後一個功能是數組鍵被傳遞數字:b [1] = 1,而不是b [] = 1,以避免問題 –