Submitting an array with a key via JQuery ajax

 

Questions


im submitting an array of values via jquery ajax, but my servlet only picks up the first value in the array, when it has many more elements.

$.ajax({
      type: "POST",
      url: "myServlet",
      data: ({'item':itemsArr})     
});

the array looks something like: var lovelyArray = ["cake", "thong", "supermanDoll"];

comes out the other side like: &item=cake .. and thats it.

i’m expecting it to come out like item=cake&item=thong&item=supermanDoll

Any help is much appreciated on this matter.

Thanks.

 

 

————————————————-

Answer

You can use $.param to serialize your array, like this:

$.ajax({
      type: "POST",
      url: "myServlet",
      data: $.param({'item': itemsArr})  // item[]=cake&item[]=thong&item[]=supermanDoll
});

The above output assumes that you are using jQuery 1.4+. If you are using jQuery 1.3.2 or earlier, the output will look like:

item=cake&item=thong&item=supermanDoll

ajax,javascript,jquery,servlets,tomcat

Facebook Comments

Post a comment