你如何发送数组作为(jQuery的)Ajax请求的一部分 [英] How do you send an array as part of an (jquery) ajax request

查看:198
本文介绍了你如何发送数组作为(jQuery的)Ajax请求的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图发送一个数组作为一个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);
    }
  });
}

这篇关于你如何发送数组作为(jQuery的)Ajax请求的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆