我有一个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
。因此,如果用户选择&#34; Colors&#34;,他们将看到3种颜色中的<ul>
。如果他们选择了#34; Pets&#34;,他们会看到2只宠物中的<ul>
。
到目前为止,我所拥有的代码只是伪代码,我似乎无法通过树木看到&#34;森林&#34;。关于GSP / jQuery的确切变化我需要做些什么才能让它发挥作用?
请注意:我只对这个(非sclabale)解决方案感兴趣,因此地图/模型会在页面加载时一次注入JS变量。
答案 0 :(得分:0)
这是一个完整的答案:
// widgets.gsp
<%@ page import="grails.converters.JSON" expressionCodec="none" %>
// other gsp stuff
<g:javascript>
var widgetMap = ${widgetMap as JSON};