从客户端操作Grails/jQuery中的映射



我有一个Grails(2.3.6)控制器,看起来像这样:

class WidgetController {
    def index() {
        Map<String, List<String>> widgetMap = getSomehow()
        render (
            view: "widgets",
            model: [ widgetMap: widgetMap ]
        )
    }
}

假设在运行时,widgetMap将等效于以下内容:

Map<String, List<String>> widgetMap = []
List<String> colors = []
List<String> pets = []
colors << "Red"
colors << "Blue"
colors << "Green"
pets << "Dog"
pets << "Cat"
widgetMap.put("Colors", colors)
widgetMap.put("Pets", pets)

widgets.gsp

<!DOCTYPE html>
<html>
<head>
    <!-- Omitting a bunch of stuff for brevity -->
</head>
<body>
    <g:select name="widgetMapSel" from="${widgetMap}" />
    <ul id="widgetList">
    </ul>
    <g:javascript>
        // Save the Grails-injected 'widgetMap' to JS.
        var widgetMap = ${widgetMap};
        $.("#widgetMapSel").on('change', function() {
            var select = this;
            var selectedOpt = select.value; // "Colors", "Pets", etc.
            // Query 'widgetMap' for key that matches the text inside the 'selectedOpt'
            var key = ???
            // Get list of values associated with key
            var list = widgetMap[key];      // ["Red", "Blue", "Green"] - OR - ["Dog", "Cat"], etc.
            // Clear the current 'widgetList' list.
            $.("#widgetList").empty();
            // Populate the 'widgetList' with our new list.
            $.each(...) {
                $.("#widgetList").append("<li>" + list[i] + "</li>);
            }
        });
    </g:javascript>
</body>
</html>

我需要将widgetMap存储为 JS/jQuery 变量,然后根据用户当前所做的选择动态清除/填充该变量中的widgetList。因此,如果用户选择"颜色",他们将看到 3 种颜色的<ul>。如果他们选择"宠物",他们会看到 2 只宠物的<ul>

到目前为止,我

拥有的代码只是伪代码,我似乎看不到"穿过树木的森林"。关于我需要进行哪些确切的GSP/jQuery更改才能使其工作的任何想法?


请注意:我只对这个(非 sclabale)解决方案感兴趣,即在页面加载时将地图/模型一次性注入到 JS 变量中。

这是一个完整的答案:

// widgets.gsp
<%@ page import="grails.converters.JSON" expressionCodec="none" %>
// other gsp stuff
<g:javascript>
    var widgetMap = ${widgetMap as JSON};

最新更新