在 Struts2 中使用 AJAX 基于另一个选择菜单填充一个选择菜单 [英] Populating one select menu based on another select menu using AJAX in Struts2

查看:25
本文介绍了在 Struts2 中使用 AJAX 基于另一个选择菜单填充一个选择菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次尝试在 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>

发送“验证码”获取 | 15天全站免登陆