0

I wanna post a lot of same field values to server in Jquery ajax, I can do it via adding all values to url, but I wanna know how to do it using data attribute. There must have an equal way.

$.ajax({
    type : "POST",
    url : 'abc.action?name=5&name=6',
    data : {
        name : 2,
        name : 3
    },
    error : function() {
        console.error("operate failed");
    },
    success : function(data) {
        console.log(data);
    }
});

In above code, the request send 5, 6 and 3 to server, but not 2. enter image description here

Maybe this problem will be different using different server side, I use Struts2.

Leo Lee
  • 468
  • 5
  • 16

2 Answers2

2

You seem to be looking for an array.

Just define a variable name as an array. And push all the values into it, and once it has all the values then send it in the ajax request.

name = [];

name.push("2");
name.push("3");

$.ajax({
    type : "POST",
    url : 'abc.action',
    data : {
        name : name
    },
    error : function() {
.....
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
  • why the same param using twice: `abc.action?name=5&name=6` ? – Riad Jul 28 '16 at 09:34
  • @Riad Sorry my bad, I missed it while copy pasting from the OP's question. - Fixed. – Mohd Abdul Mujib Jul 28 '16 at 09:35
  • @Riad We can accept the values at server side using an array field, like java Struts2 `private int[] name;` – Leo Lee Jul 28 '16 at 09:44
  • @MohdAbdulMujib your code will finally send params to server like `name[] 2 name[] 3`, this is not what I wanted, it changed the param from `name` to `name[]`. – Leo Lee Jul 28 '16 at 09:48
  • @LeoLee Logically thinking, A variable can contain one value at most. If we need to store more than one value into the same variable then we do it in the form of an `array` or `dumb data object`, and you are seeing the former in your previous comment. – Mohd Abdul Mujib Jul 28 '16 at 09:52
  • @MohdAbdulMujib but `abc.action?name=5&name=6` do can send 5 and 6 to server at the same time, at least in jsp language. E.g. - http://stackoverflow.com/q/9768509/2205911 – Leo Lee Jul 28 '16 at 09:58
  • Okay and how do you access those values, like say you need to access the second value. And Btw the `duplicate keys in $_GET url` behavior is not defined in HTML specs and is left upto the serverside framework/language to handle it accordingly, as discussed here http://stackoverflow.com/a/1746566/807104. – Mohd Abdul Mujib Jul 28 '16 at 10:03
  • @MohdAbdulMujib Maybe this written way is really not suitable for php, but it's ok for java. – Leo Lee Jul 28 '16 at 10:06
0

this is because you are overwriting the same variable name again and again. If there are more than one value than put it into an array and send it. And one more thing, there is no need to specify the variable in url like:

url : 'abc.action?name=5&name=6',

because you are providing variable in data: {} itself.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59