gpt4 book ai didi

ajax - 如何通过使用Grails 2.1.0中的AJAX从Grails Controller中获取数据来单击相同形式的搜索按钮时更新2个文本字段

转载 作者:行者123 更新时间:2023-12-02 16:00:50 24 4
gpt4 key购买 nike

我有一个 Controller (SearchController),它通过单击搜索按钮(在myview.gsp内)获取数据,我想用我 Controller (SearchController)中的数据填充同一myview.gsp中存在的2个文本字段。需要做ajax调用,因为我只想填充2个字段并且不想重新加载包含其他有值(value)信息的页面。我如何实现它,请指导我

这是我的 Controller

def searchItem() {

def itemFound = MyService.searchP20Code(params["item"])

def resultMap = [:]
if (itemFound!=null)

{



resultMap.put("CODE",itemFound[1])
resultMap.put("DESC",itemFound[2])

}


println "Result:"+resultMap



session.setAttribute("searchResult", resultMap)
render(view: myview" )


}

myview.gsp
          myview.gsp 


<div class="leftPanel filter-label">
<a href="#" class="tt"> <g:message
code="Normal.label.Code" />

</a>
</div>
<div class="rightPanel filter-field-wrapper">
<input type="text"
name="Code" maxlength="30"
value=""
id="i_code" />
</div>
</div>

<div class="formLables">

<div class="leftPanel filter-label">
<a href="#" class="tt"> <g:message
code="Normal.label.Description" />
</a>
</div>
<div class="rightPanel filter-field-wrapper">
<input type="text"
name="Desc" maxlength="30"
onkeyup="fieldMaxlength(&#39;material_code&#39;)" value=""

id="i_description" />
</div>
</div>



<g:actionSubmit

value="${message(code:'Normal.button.search', default: 'Search Code')}"
action="searchItem" />

请帮助我如何使用ajax在myview.gsp onclicking搜索按钮上仅更新这两个文本字段。我正在使用grails 2.1.0

最佳答案

Here您可以找到带有Grails内置Ajax支持的详细示例。

您还可以使用JQuery(example here)

编辑:

您的 Controller 需要如下所示:

import grails.converters.JSON

class ExampleController {
....

def searchItem() {

def itemFound = MyService.searchP20Code(params["item"])

def resultMap = [:]
if (itemFound!=null) {
resultMap.put("CODE",itemFound[1])
resultMap.put("DESC",itemFound[2])
}


println "Result:"+resultMap



//session.setAttribute("searchResult", resultMap)
render(resultMap as JSON )


}
}

和你的gsp
<head>
...
<g:javascript plugin="jquery" library="jquery" src="jquery/jquery-{WRITE_YOUR_VERSION_HERE}.js"/>
<script>
function callAjax(e){
e.preventDefault();
$.ajax({
url: "example/search",
type:"post",
dataType: 'json',
success: function(data) {
console.log(data);
$("input[name='Code']").val(data.CODE);
$("input[name='Desc']").val(data.DESC);
}
});
}
</script>
...
</head>
<body>
....
<input type="submit" value="Call Ajax Function" onclick="callAjax()">
....
</body>

关于ajax - 如何通过使用Grails 2.1.0中的AJAX从Grails Controller中获取数据来单击相同形式的搜索按钮时更新2个文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31152807/

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