我想在Struts2中第一次使用AJAX.因此,我对此并不十分了解.
有两个< s:select> s,一个包含在页面加载时加载的国家列表,另一个包含与从国家/地区菜单中选择的国家相对应的状态列表.
因此,应该在国家/地区菜单触发的onchange JavaScript事件上初始化状态菜单.
这种JavaScript函数的不完整版本如下.
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:选择>对于国家:
<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:选择>对于州:
<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请求,该请求映射到动作类中的方法,如下所示.
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初始化/填充< s:select>国家菜单?
我之前在Spring MVC中使用过Jackson和Gson的JSON.例如,使用Gson,可以简单地映射JSON响应,如下所示(为简单起见,使用Servlet).
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可以写成如下.
$('#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填充.
Struts2怎么样?如何填充< s:select>基于另一个< s:select>?
解决方法:
与Struts2中的方法相同,但您可以使用该操作代替servlet.例如
@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
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);
}
},
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。