简体   繁体   English

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

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

I tried to send an array as part of an ajax request like this: 我试图将数组作为ajax请求的一部分发送,如下所示:

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: 我想看看我在servlet中得到了什么,所以我使用了这一行:

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

Which returned {} suggesting an empty map. 其中返回了{}表明地图为空。

Firebug tells me I am getting a 400 bad request error Firebug告诉我我收到400 bad request错误

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. 如果我将诸如attribute=value类的queryString作为“数据”发送,那么一切工作正常,因此与不能按原样发送数组有关。 What do I have to do to get that data into the servlet for further processing. 我必须怎么做才能将该数据放入servlet进行进一步处理。 I don't want to pull it out and turn it into a queryString in the JS if I can avoid it. 如果可以避免,我不想将其拉出并变成JS中的queryString。

EDIT: I used the .serializeArray() (jQuery) function before sending the data. 编辑:我在发送数据之前使用了.serializeArray()(jQuery)函数。 I don't get the 400 but nothing useful is being sent through. 我没有得到400,但是没有发送任何有用的信息。

You have to send an object which you first stringify with JSON.stringify. 您必须发送一个首先使用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 根据有关jQuery.Ajax()方法的data设置的jQuery文档

If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting 如果value是一个Array,则jQuery根据传统设置的值使用相同的键序列化多个值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM