gpt4 book ai didi

grails - 异步调用Controller-适用于州和县

转载 作者:行者123 更新时间:2023-12-02 15:25:49 26 4
gpt4 key购买 nike

在Grails中,我需要制作一个 Controller 方法,该方法将填充“州和县”下拉列表表单域,以便在选择一个州时仅将该州的县填充到“县”下拉列表中。

一位同事告诉我,这是Grails中的异步调用,但是我是Grails中的新手,我真的不知道那是什么或如何开始。任何帮助将不胜感激。

这是我的代码段:

当前使用Grails 2.43。我有两个域类(州和县),以及两个针对州和县的“选择”下拉列表。

表单元素:

<g:select name="locationState" class="form-control" from="${....State.list().sort{it.orderNumber}}">

<g:select name="locationCounty" class="form-control" from="${...State.FindByName(it.orderNumber).counties}">

以下是示例类:
 class State {

static hasMany = [county:County]

String name
String value
int orderNumber = 0

static constraints = {
name nullable:false, maxSize:50, blank:false
value nullable:false, maxSize:100, blank:false
}

String toString(){
"$value"
}

static mapping = {
table 'state'
cache: 'read-write'
columns{
id column:'id'
name column:'name'
value column:'value'
orderNumber column:'order_number'
}
id generator: 'assigned'
}
}


class County {

State state
String county

static constraints = {
state nullable:false
county nullable:false, maxSize:100, blank:false
}

String toString(){
"${state.name} - $county"
}

static mapping = {
table 'county'
cache: 'read-write'
columns{
id column:'id'
county column:'county'
state column:'state_id'
}
id generator: 'assigned'
}
}

最佳答案

注释中链接的异步指南适用于进行程序化异步调用。例如,如果您有两个计算量大的方法调用(或需要网络I / O的方法调用),则可以使用线程(大致)并行运行它们。 Grails提供了许多不同的帮助程序,以使这种异步编程变得非常容易。

但是,这不太可能是您执行GORM查询所需要的。您要填充第二个选择框。您可以通过以下两种方法来完成此操作:选择状态后重新加载页面,或使用JavaScript填充框。我假设您想做后者。 Grails确实提供了工具(例如<g:remoteFunction />标记)来处理此问题,而无需编写您自己的JavaScript,但是Grails AJAX库已被弃用,因此不建议使用。

相反,您应该只编写自己的JavaScript。我将向您展示一种使用jQuery的技术:

在您的 View 中,初始化两个选择,但第二个应初始化为空。我们还将为它们提供ID,以使其更易于从jQuery中进行选择:

<g:select name="locationState"
class="form-control"
from="${....State.list().sort{it.orderNumber}}"
id="location-state" />
<g:select name="locationCounty"
class="form-control"
from="${[]}"
id="location-county" />

然后,我们将需要在 Controller 上公开一个操作,以在用户选择状态时加载县:
def loadCountiesByState() {
def state = params.state
def counties = State.findByValue(state).counties
render g.select(name: 'locationCounty', class: 'form-control',
from: counties, id: 'location-county')
}

您只需将浏览器指向 /app-name/controller-name/loadCountiesByState?state=CA即可测试此部分。我不知道您的数据是如何建模的,因此您可能需要更改 State.findByValue(state)部分以适合您的需求。

现在,我们只需要使用一些JavaScript连接控件即可。确保您包含jQuery。
<script type="text/javascript">
$(function() {
$('#location-sate').change(function() {
var state = $(this).val();
$.ajax({
url: '/app-name/controller-name/loadCountiesByState',
date: { state: state },
success: function(data) {
$('#location-county').replaceWith(data);
}
});
});
});
</script>

这将用新的选择替换下拉列表,该选择应完全由县填充。

关于grails - 异步调用Controller-适用于州和县,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27723149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com