我使用以下代码将一些信息发送到我的 servlet 来处理数据:
$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) {
});
但是当我尝试接收它时,我得到 null,这就是我在 servlet 中接收它的方式:
String arr= request.getParameter("addArray");
System.out.println(arr);
更新2:这是最新的代码
我的小服务程序:
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);
}
My 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) {
});