如何使用 jQuery $.ajax 将请求参数数组发送到 servlet?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13241668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send request parameter array to servlet using jQuery $.ajax?
提问by IbrahimAsad
I would like to send JavaScript array to servlet using jQuery $.ajax
.
我想使用 jQuery 将 JavaScript 数组发送到 servlet $.ajax
。
var json=[1,2,3,4];
$.ajax({
url:"myUrl",
type:"POST",
dataType:'json',
success:function(data){
// codes....
},
data:json
});
When I use
当我使用
request.getParameter("json");
request.getParameterValues("json");
It returns null.
它返回空值。
How can I access the values?
如何访问这些值?
回答by Raunak Agarwal
Send array as value of JS object so you end up as {json:[1,2,3,4]}
.
将数组作为 JS 对象的值发送,这样你最终会成为{json:[1,2,3,4]}
.
var json=[1,2,3,4];
$.ajax({
url:"myUrl",
type:"POST",
dataType:'json',
data: {json:json},
success:function(data){
// codes....
},
});
In servlet, you need to suffix the request parameter name with []
.
在 servlet 中,您需要在请求参数名称后缀[]
.
String[] myJsonData = request.getParameterValues("json[]");
jQuery appends them in order to be friendly towards weak typed languageslike PHP.
jQuery 附加它们是为了对弱类型语言(如 PHP)友好。
回答by DWolf
You have to convert your array to a JSON type so instead of [] it needs to read
您必须将数组转换为 JSON 类型,因此它需要读取而不是 []
var array = [ 1, 2, 3, 4 ];
to do this you need to call
要做到这一点,你需要打电话
var json = JSON.stringify(array)
then you can pass it into your ajax call
然后你可以将它传递到你的ajax调用中
$.ajax({ url:"myUrl",
type:"POST",
data: json,
dataType:'json',
success:function(data){
// codes....
}})
回答by Shubham Gupta
Try using below script -
尝试使用以下脚本 -
jQuery.ajax({
url : "your API",
type : "POST",
dataType:'json',
data: JSON.stringify({ jsonData: data }),
contentType: "application/json",
success : function(response) {
//do the needful.
},
error : function(jqXHR, textStatus,
errorThrown) {
var x = 1;
closeLoader();
}
});
handle the request in the controller as below -
处理控制器中的请求如下 -
@RequestMapping(value="your url", method = RequestMethod.POST)
public Map<String, Object> verifyRefundRequested(@RequestBody String data) throws UnsupportedEncodingException{
Map<String, Object> responseMap = null;
Gson g = new Gson();
responseMap = g.fromJson(data, Map.class);
List<String> s = (List<String>) responseMap.get("jsonData");
//iterate list and process
// return map
}
回答by Shubham Gupta
You need to post your javascript data object like this..
你需要像这样发布你的javascript数据对象..
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.post/
$.post("test.php", { name: "John", time: "2pm" },
function(data) {
alert("Data Loaded: " + data);
});