Pass the list in the background, JS traversal processing

1. Convert the list or map into json in the background JSON.toJSONString()

2. The front desk obtains objects through JSON.parse('${list}')

Sample code:

1. Background code, use JSON.toJSONString(categoryList)

@RequestMapping("/toList")
    public String toList(Model model) {

        // 获取对象LIST
        List<Object> categoryList = service.queryList();
        model.addAttribute("categoryList", JSON.toJSONString(categoryList));
        // 传递map 对象
        Map<String, Object> reMap = new HashMap<>();
        reMap.put("edit ","1111");
        model.addAttribute("map", JSON.toJSONString(reMap));

        // 跳转页面
        return MODEL_PATH + "List";

    }

2. Foreground code

    // 获取list
    var categoryList = JSON.parse('${categoryList}');
    // 循环list
    for (var i = 0; i < categoryList.length; i++) {
                html += "<option value='" + categoryList[i].id + "'>" + categoryList[i].categoryName + "</option>";
            }

// Get the attributes in the map 

    // 获取map
    var map= JSON.parse('${map}');
    // 获取map 的属性
    var edit = map.edit;
 
 

Extended tips for loop use each instead

        //-------扩展提示 for循环可以使用each代替
        $.each(data, function (i, item) {
            //拼接每一个选项
            htmls += '<option value="'+ item.id +'">'+ item.categoryName +'</option>';
            // 默认获取第一个
            if (i == 0) {
                objectList = item.list;
            }    
        });

        // 箭头函数遍历
        let  array =[];
        list.forEach(item => {
          array.push(item.value());
        })

Guess you like

Origin blog.csdn.net/qq_37570710/article/details/127900075