我用下面的代码来发送一些信息给我的servlet处理数据:通过在角JS AJAX调用发送阵列
$http({
method: "GET",
url: "http://localhost:8080/purchase/AddInfo",
data: {
addArray : "sample"
}
})
.success(function (data, status, headers, config) {
typesHash.push({id:data.id,name : data.name, price : data.price,unit:2.5 });
})
.error(function (data, status, headers, config) {
});
和它完美; 但你可以看到我想要发送的参数作为数组不是字符串,可以说我有一个数组如下:
var typesHash=[
{id:'1', name : 'lemon', price : 100,unit:2.5 },
{id:'2', name : 'meat', price : 200,unit:3.3 }];
现在我想这个数组发送到服务器,一个快速的和丑陋方式是循环通过我有的数组,并发送信息作为字符串,但我相信应该有更好的方法,任何人都可以帮助吗?
更新:因为它是建议我改变了我的代码如下:
$http({
method: "post",
url: "http://localhost:8080/purchase/AddInfo",
addArray : typesHash
})
.success(function (data, status, headers, config) {
typesHash.push({id:data.id,name : data.name, price : data.price,unit:2.5 });
})
.error(function (data, status, headers, config) {
});
,但我得到空当我尝试rceive它,这是我收到它在我的servlet:
String arr= request.getParameter("addArray");
System.out.println(arr);
更新2:这是最更新的代码
我的servlet:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String actionType = request.getParameter("addArray");
System.out.println(actionType);
PrintWriter out = response.getWriter();
response.setContentType("text/html");
String str = "{ \"id\": \"1\",\"name\": \"ali\",\"price\": \"100000\"}";
// System.out.println(str);
out.println(str);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
我的JS:
$http({
method: "post",
url: "http://localhost:8080/purchase/AddInfo",
data: { addArray : typesHash }
})
.success(function (data, status, headers, config) {
typesHash.push({id:data.id,name : data.name, price : data.price,unit:2.5 });
})
.error(function (data, status, headers, config) {
});
嗯,我明白了!我认为这是你需要的https://docs.angularjs.org/api/ng/service/$http – 2015-02-07 22:52:33
嘿这条线的输出是什么“System.out.println(arr);”在servlet控制台中?并且不要使用get post,因为在java中获得大小限制。 – squiroid 2015-02-08 06:03:09
还有一件事这一行addArray:typesHash,应该是数据:typesHash你的建议system.println – squiroid 2015-02-08 06:05:11