views:

43

answers:

1

I have a spring controller with a request mapping as follows

@RequestMapping("/downloadSelected")
public void downloadSelected(@RequestParam String[] ids) {
    // retrieve the file and write it to the http response outputstream
}

I have an html table of objects which for every row has a checkbox with the id of the object as the value. When they submit, I have a jQuery callback to serialize all ids. I want to stick those ids into an http request parameter called, "ids" so that I can grab them easily.

I figured I could do the following

var ids = $("#downloadall").serializeArray();

Then I would need to take each of the ids and add them to a request param called ids. But is there a "standard" way to do this? Like using jQuery?

+2  A: 

I don't know about "standard way", but this is how I would do it.

var ids = $("#downloadall").serializeArray();

will give you a dataset on the form (only the checked items presented):

[{name:"foo1", value:"bar1"}, {name:"foo2", value:"bar2"}]

To feed this to jQuery's .ajax() just:

$.ajax({
  url: <your url>,
  data: ids.map(function (i) {return i.name+'='+i.value;}).join('&')
});

The Array.map() is not compatible with all browsers yet so you better have this code on your page too:

if (!Array.prototype.map) {
  Array.prototype.map = function(fun /*, thisp*/) {
    var len = this.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }
    return res;
  };
}

This code snippet I got from mozilla developer center.

I didn't put them in a ?ids=... param, but this way they are easy to access on server side. You can always just modify the map function to fit your needs.

MyGGaN
Or, just use the jQuery map function: http://api.jquery.com/jQuery.map/
jvenema
Yes, that's a good idea too! I like jQuery, they always seem have what you need :)
MyGGaN