你如何发送数组作为(jQuery的)Ajax请求的一部分数组、jQuery、Ajax

2023-09-11 00:44:03 作者:落红尘°

我试图发送一个数组作为一个Ajax请求喜欢这一段:

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); 
    }
  });
}

我想看看我回来在servlet,所以我用这一行:

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

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

这回 {} 这意味着一个空映射。

Which returned {} suggesting an empty map.

萤火告诉我,我得到一个 400错误的请求错误

Firebug tells me I am getting a 400 bad request error

如果我发送一个查询字符串如属性=值的'数据',那么一切正常,所以它必须与不能够因为是发送一个数组。我有什么做的就是这些数据到servlet进行进一步的处理。我不想把它拉出来,把它变成了JS一个查询字符串,如果我能避免它。

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.

编辑:我​​用.serializeArray()(jQuery的)函数发送数据之前。我不明白的400,但没有什么可被发送过。

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

推荐答案

您需要发送您第一次使用字符串化的JSON.stringify对象。

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

是这样的:

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);
    }
  });
}