前端ajax写法:
function middleCategoryChange(url) { var middleCategory = $("select[name='middleCategory']").val(); var json ={}; json.middleCategory = middleCategory; var windowToken = $('input[name="windowToken"]').val(); $.ajax({ async: true, headers: { "X-CSRF-Token": windowToken }, url : url, type : "post", //使用post方法 contentType: "application/json", //指定为json格式,不然后台接受会报错 data : JSON.stringify(json), // 用JSON.stringify转换为json对象,不然后台接受的值不对 cache: false, dataType: "json" }).done(function(data, status, jqxhr) { var minorCategoryList = data[0]; var subCategoryList = data[1]; if (minorCategoryList) { $("select[name='minorCategory']").empty(); for(var i = 0; i < minorCategoryList.length; i++) { $("select[name='minorCategory']").append("<option value='" + minorCategoryList[i].categoryCd + "'>" + minorCategoryList[i].categoryNm + "</option>"); } } if (subCategoryList) { $("select[name='subCategory']").empty(); for(var i = 0; i < subCategoryList.length; i++) { $("select[name='subCategory']").append("<option value='" + subCategoryList[i].categoryCd + "'>" + subCategoryList[i].categoryNm + "</option>"); } } }).fail(function(data, status, jqxhr) { alert("error!"); }); }
后台代码:
controller
@RequestMapping("minorCategory/search") @ResponseBody public List<List<CategoryEntity>> minorCategorySearch( @RequestBody ProductFormEntity formEntity) throws JSONException { // 后台接受参数时需要加上 @RequestBody注解,头部需要加上@ResponseBody注解 List<CategoryEntity> minorCategoryList = categoryUtil.getMinorCategoryList(formEntity.middleCategory); List<CategoryEntity> subCategoryList = categoryUtil.getSubCategoryList(formEntity.middleCategory, null); List<List<CategoryEntity>> list = new ArrayList<>(); list.add(minorCategoryList); list.add(subCategoryList); // 因为需要返回两个List,所以返回的是list的list return list; }
formEntity
public String middleCategory; public String minorCategory; public String subCategory;