开发者

How do you send an array as part of an (jquery) ajax request

开发者 https://www.devze.com 2023-02-03 09:10 出处:网络
I tried to send an array as part of an ajax request like this: var query = []; // in between I add some values to \'query\'

I tried to send an array as part of an ajax request like this:

var query = [];
// in between I add some values to 'query'
$.ajax({
    url: "MyServlet", 
    data: query,
    dataType: "json",  
    success: function(noOfResults) { 
    alert(noOfResults); 
    }
  });
}

I wanted to see what I get back in the servlet, so I used this line:

System.out.println(request.getParameterMap().toString());

Which returned {} suggest开发者_开发百科ing an empty map.

Firebug tells me I am getting a 400 bad request error

If I send a queryString like attribute=value as the 'data' then everything works fine, so it has to do with not being able to send an array as is. What do I have to do to get that data into the servlet for further processing. I don't want to pull it out and turn it into a queryString in the JS if I can avoid it.

EDIT: I used the .serializeArray() (jQuery) function before sending the data. I don't get the 400 but nothing useful is being sent through.


You have to send an object which you first stringify with JSON.stringify.

like this:

var query = [];
// in between I add some values to 'query'
$.ajax({
    url: "MyServlet",
    data: JSON.stringify({ nameParameter: query })
    dataType: "json",
    success: function(noOfResults) {
        alert(noOfResults);
    }
  });
}


Just try to send the data as name/value pair (which is expected). Like

var query = ["data1","data2"];
// in between I add some values to 'query'
$.ajax({
    url: "MyServlet", 
    data: {'query' : query},
    success: function(noOfResults) { 
    alert(noOfResults); 
    }
  });
}

You should get the data at server side like this

query => Array ( [0] => data1 [1] => data2 )

As per the jQuery documentation for data setting of jQuery.Ajax() method

If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting

0

精彩评论

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