问题描述
我第一次尝试在 Struts2 中使用 AJAX.因此,我对此没有确切的想法.
I'm trying to use AJAX at very first time in Struts2. Therefore, I do not have precise idea about it.
有两个
,一个保存页面加载时加载的国家列表,另一个保存与从国家菜单中选择的国家相对应的国家列表.
There are two <s:select>
s, one holds a list of countries which is loaded on page load and another holds a list of states that corresponds to the country selected from the country menu.
因此,应该在国家菜单触发的 onchange
JavaScript 事件上初始化状态菜单.
Therefore, the state menu should be initialized on the onchange
JavaScript event triggered by the country menu.
此类 JavaScript 函数的不完整版本如下.
The incomplete version of such a JavaScript function is as follows.
var timeout;
var request;
function getStates(countryId)
{
if(!request)
{
if(countryId===""||countryId===null||countryId===undefined||isNaN(countryId))
{
$('#stateList').html("Write an empty <select>");
alert("Please select an appropriate option.");
return;
}
request = $.ajax({
datatype:"json",
type: "GET",
contentType: "application/json",
url: "PopulateStateList.action?countryId="+countryId,
success: function(response)
{
if(typeof response==='object'&&response instanceof Array) //Array or something else.
{
$('#stateList').html(writeResponseSomeWay);
$('#temp').remove();
}
},
complete: function()
{
timeout = request = null;
},
error: function(request, status, error)
{
if(status!=="timeout"&&status!=="abort")
{
alert(status+" : "+error);
}
}
});
timeout = setTimeout(function() {
if(request)
{
request.abort();
alert("The request has been timed out.");
}
}, 300000); //5 minutes
}
}
国家:
<s:select id="country"
onchange="getStates(this.value);"
name="entity.state.countryId"
list="countries" value="entity.state.country.countryId"
listKey="countryId" listValue="countryName"
headerKey="" headerValue="Select"
listTitle="countryName"/>
用于状态:
<s:select id="state"
name="entity.stateId"
list="stateTables" value="entity.state.stateId"
listKey="stateId" listValue="stateName"
headerKey="" headerValue="Select"
listTitle="stateName"/>
上述 JavaScript/jQuery 函数向 PopulateStateList.action
发送一个 AJAX 请求,该请求被映射到一个动作类中的方法,如下所示.
The above JavaScript/jQuery function sends an AJAX request to PopulateStateList.action
which is mapped to a method in an action class as follows.
List<StateTable>stateTables=new ArrayList<StateTable>(); //Getter only.
@Action(value = "PopulateStateList",
results = {
@Result(name=ActionSupport.SUCCESS, location="City.jsp"),
@Result(name = ActionSupport.INPUT, location = "City.jsp")},
interceptorRefs={@InterceptorRef(value="modelParamsPrepareParamsStack", params={"params.acceptParamNames", "countryId", "validation.validateAnnotatedMethodOnly", "true", "validation.excludeMethods", "getStateList"})})
public String getStateList() throws Exception
{
System.out.println("countryId = "+countryId);
stateTables=springService.findStatesByCountryId(countryId);
return ActionSupport.SUCCESS;
}
当在其菜单中选择一个国家并检索作为查询字符串参数提供的 countryId
但如何返回/映射此列表时,将调用此方法,stateTables初始化/填充状态菜单的
?
This method is invoked, when a country is selected in its menu and the countryId
supplied as a query-string parameter is retrieved but how to return/map this list, stateTables
to initialize/populate <s:select>
of state menu?
我之前在 Spring MVC 中使用了 JSON 和 Jackson 和 Gson.例如,使用 Gson,JSON 响应可以简单地映射如下(为了简单起见,使用 Servlet).
I have earlier used JSON with Jackson and Gson in Spring MVC. Using Gson, for example, a JSON response could simply be mapped like as follows (using a Servlet for the sake of simplicity).
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "AjaxMapServlet", urlPatterns = {"/AjaxMapServlet"})
public class AjaxMapServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Map<String, String>map=new HashMap<String, String>();
map.put("1", "India");
map.put("2", "America");
map.put("3", "England");
map.put("4", "Japan");
map.put("5", "Germany");
Type type=new TypeToken<Map<String, String>>(){}.getType();
Gson gson=new Gson();
String jsonString=gson.toJson(map, type);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonString);
}
}
在JSP中,这个Map
可以写成如下.
and in JSP, this Map
could be written as follows.
$('#btnMap').click(function() {
$.get('/TestMVC/AjaxMapServlet', function(responseJson) {
var $select = $('#mapSelect');
$select.find('option').remove();
$('<option>').val("-1").text("Select").appendTo($select)
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
});
});
})
<input type="button" id="btnMap" name="btnMap" value="Map"/><br/>
<select id="mapSelect" name="mapSelect"><option>Select</option></select>
将在按下给定按钮时填充,btnMap.
<select> will be populated on pressing the given button, btnMap.
Struts2 怎么样?如何根据另一个 填充 ?
What about Struts2? How to populate an <s:select> based on another <s:select>?
推荐答案
与在 Struts2 中执行的方式相同,但您可以使用操作代替 servlet.例如
The same way you can do it in Struts2, but instead of servlet you can use the action. For example
@Action(value="/PopulateStateList", results=@Result(type="json", params = {"contentType", "application/json", "root", "map"}))
public class AjaxMapAction extends ActionSupport {
Long countryId; //getter and setter
Map<String, String> map=new HashMap<String, String>();
public Map<String, String> getMap() {
return map;
}
@Override
public String execute() throws Exception {
map.put("1", "India");
map.put("2", "America");
map.put("3", "England");
map.put("4", "Japan");
map.put("5", "Germany");
return SUCCESS;
}
}
现在,您可以在客户端使用 JSON
Now, you can use the JSON on the client
success: function(response)
{
if(typeof response==='object')
{
var $select = $('#state');
$select.find('option').remove();
$('<option>').val("-1").text("Select").appendTo($select)
$.each(response, function(key, value) {
$('<option>').val(key).text(value).appendTo($select);
}
},
这篇关于在 Struts2 中使用 AJAX 基于另一个选择菜单填充一个选择菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2
查看全文
(adsbygoogle = window.adsbygoogle || []).push({});
相关文章
在Struts2中使用AJAX基于另一个选择菜单填充一个选择菜单;
使用Jquery Mobile让选择菜单在另一个选择菜单中选择一个值;
第二个选择菜单根据第一个选择菜单更改;
Rails 4 - 基于嵌套形式的第一个选择菜单中的选择动态填充第二个选择菜单;
Rails 4-基于嵌套形式的第一个选择菜单中的选择动态填充第二个选择菜单;
硒:如何从选择菜单中选择一个选项?;
Selenium:如何从选择菜单中选择一个选项?;
在jQuery选择菜单中选择下一个选项;
iOS 6选择菜单vs iOS 7选择菜单;
Powershell选择菜单;
jQuery选择:如何选择1个选项值并在另一个选择菜单中删除相同的选项?;
根据另一个选择填充一个下拉菜单;
如何使用选择菜单和link_to重定向到另一个页面-Ruby on Rails;
Linux脚本选择菜单;
jQuery 选择菜单 wordpress;
动态依赖选择菜单;
在选择菜单的动作中嵌入2个参数;
在选择第一个下拉菜单时填充另一个下拉菜单;
Rails-Ajax选择菜单仅触发一次?;
从另一个选择中选择一个下拉菜单;
在 PHP 中创建一个选择菜单,默认从 MySQL 数据库中选择;
使用键盘选择菜单项;
在bash中创建选择菜单;
多字符批次选择菜单;
引导程序选择菜单样式;
(adsbygoogle = window.adsbygoogle || []).push({});
(adsbygoogle = window.adsbygoogle || []).push({});
Java开发最新文章
Tomcat 404错误:原始服务器没有找到目标资源的当前表示,或者不愿意透露该目录的存在;
由于缺少ServletWebServerFactory bean,无法启动ServletWebServerApplicationContext;
无法反序列化的java.util.ArrayList实例出来VALUE_STRING的;
什么是AssertionError?在这种情况下,我应该从我自己的代码中抛出?;
JSON反序列化投掷例外 - 无法反序列化的java.util.ArrayList实例出来START_OBJECT令牌;
Maven构建错误 - 无法执行目标org.apache.maven.plugins:Maven的组装插件:2.5.5;
正确使用Optional.ifPresent();
获取异常(org.apache.poi.openxml4j.exception - 没有内容类型[M1.13])阅读使用Apache POI XLSX文件时?;
SpringBoot - 制作jar文件 - 在META-INF / spring.factories中找不到自动配置类;
HTTP状态404 - 请求的资源(/)不可用;
热门教程
Java教程
Apache ANT 教程
Kali Linux教程
JavaScript教程
JavaFx教程
MFC 教程
Apache HTTP客户端教程
Microsoft Visio 教程
热门工具
Java 在线工具
C(GCC) 在线工具
PHP 在线工具
C# 在线工具
Python 在线工具
MySQL 在线工具
VB.NET 在线工具
Lua 在线工具
Oracle 在线工具
C++(GCC) 在线工具
Go 在线工具
Fortran 在线工具
var eskeys = '在,struts2,中,使用,ajax,基于,另一个,选择,菜单,填充,一个,选择,菜单'; var cat = 'java';
登录
关闭
扫码关注1秒登录