如何使用Ajax将数组值从Javascript格式化为Java Servlet

时间:2018-10-15 01:16:24

标签: javascript java json ajax servlets

我需要你的帮助。

我使用AJAX将此数组从Javascript传递到Java Servlet。

JavaScript和AJAX代码段:

var BuildingNo = [];

$(xml).find('BUILDING').each(function(){
    BuildingNo.push($.trim(this).children('BuildingNo').text());
}

在传递给Java Servlet之前BuildingNo的值。

alert(BuildingNo);
// 00101,00102,00103,00104,00105 

当我通过Ajax将BuildingNo传递给Java Servlet时,JSON.stringify(BuildingNo)的值。

data: { BuildingNo : JSON.stringify(BuildingNo) },

alert(JSON.stringify(BuildingNo));
// ["00101","00102","00103","00104","00105"] 

这是我用来将BuildingNo传递到oldBuilding列表的Java Servlet代码段。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws (ServletException, IOException {

List <String> oldBuildingList = Arrays.asList(request.getParameter("BuildingNo");

logger.info(oldBuildingList);

// [["00101","00102","00103","00104","00105"]] -- This is a wrong format.

//I have a Java code here which captures a new list of BuildingNo from another service.

List <String> newBuildingList = new ArrayList <String>();
logger.info(newBuildingList.toString());

// [00106,00107,00108,00109,00110] -- This should be the correct format of oldBuildingList.

}

如何使用oldBuildingList获得相同格式的newBuildingList?

1 个答案:

答案 0 :(得分:1)

不要只保留为 data: { BuildingNo : BuildingNo }

以及Java Servlet List <String> oldBuildingList = Arrays.asList(request.getParameterValues("BuildingNo[]");