开发者

optimize jquery code, sending multiple arrays and simple vars via $.post

I generate this js at the server side so the arrays could have more elements

var o = 'hi world';
var keys = ['foo','bar'];
var values = ['foox', 'barzs'];
开发者_运维知识库

how can I optimize this part?:

var data = [{name:'prop', value: o}];
data.push({name: 'keys', value: 'foo'});
data.push({name: 'keys', value: 'bar'});
data.push({name: 'values', value: 'foox'});
data.push({name: 'values', value: 'barzs'});

$.post('url', $.param(data), ...);


I don't know if with a limited example you're really optimizing anything, but if you actually have large data sets, you could push the values via a loop...

again it depends on what you mean by optimize, but I'm assuming you are dealing with much larger data sets than your example, meaning having to write push statements every single value.

var data = [{name:'prop', value: o}];

for ( i in keys ) {
    data.push({ name: 'keys', value: keys[i] });
}

for ( i in values ) {
    data.push({ name: 'values', value: values[i] });
}


I believe that this would be equivalent:

$.post('url', {
  'prop': o,
  'keys': ['foo', 'bar'],
  'values': ['foox', 'barzs']
}, function() { ... });

To an extent it depends on what your server expects. Some server environments understand the HTTP convention of treating multiple instances of the same parameter as being an array-valued parameter, while others prefer parameter names to have explicit intrinsic "indexes" like "keys[0]", "keys[1]", etc. Some understand either.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜