【发布时间】:2018-12-25 16:55:34
【问题描述】:
我需要解决我的问题,我的类型 Json 我返回 {"1":"Position1","2":"Position2"} 但我需要 [{"id":1,"name":Position1},{"id":2,"name":Position2}]
这是我的方法控制器:
@GET
@RequestMapping(value = "/getPositiontMapByDepartmentId/{departmentId}")
@ResponseBody
public String getPositiontMapByDepartmentId(Employee employee, Model model,
@PathVariable("departmentId") int departmentId) {
Gson gson = new Gson();
List<Position> positionListById = positionService.findAllPositionsByDepartmentId(departmentId);
Map<Integer, String> positiontMapByDepartmentId = preparePositionMapByDepartmentId(departmentId);
positionListById.toArray();
return gson.toJson(positiontMapByDepartmentId);
}
public Map<Integer, String> preparePositionMapByDepartmentId(int departmentId) {
Map<Integer, String> positiontMapByDepartmentId = new HashMap<Integer, String>();
List<Position> positionListById = positionService.findAllPositionsByDepartmentId(departmentId);
for( Position position : positionListById){
positiontMapByDepartmentId.put(position.getId(),position.getName());
}
return positiontMapByDepartmentId;
}
我的 jsp 和 Java 脚本
$(document).ready(
function() {
$('#departmentSelect').on("change", function () {
var departmentId = $("#departmentSelect option:selected").val();
$.ajax({
type: "GET",
url: "/admin/getPositiontMapByDepartmentId/"+departmentId,
success: function (result) {
alert(result);
var result = JSON.parse(result);
var position = "";
for(var i = 0; i<result.length; i++){
position+= '<option value="' + result[i].id + '">' + result[i].name +'</option>';
}
$('#positionSelect').html(position);
}
});
});
});
当我收到{"1":"Position1","2":"Position2"} 时,我的 JS 可以改进对 html 的选择
【问题讨论】:
标签: javascript java json spring