java - 在 Struts2 中使用 AJAX 根据另一个选择菜单填充一个选择菜单

标签 java jquery ajax jsp struts2

我第一次尝试在 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:select>对于国家:

<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>对于状态:

<s:select id="state" 
          name="entity.stateId" 
          list="stateTables" value="entity.state.stateId" 
          listKey="stateId" listValue="stateName" 
          headerKey="" headerValue="Select" 
          listTitle="stateName"/>

上面的 JavaScript/jQuery 函数将 AJAX 请求发送到 PopulateStateList.action它映射到操作类中的方法,如下所示。

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 中将 JSON 与 Jackson 和 Gson 一起使用。例如,使用 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>

<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);
     }
  },

关于java - 在 Struts2 中使用 AJAX 根据另一个选择菜单填充一个选择菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38763337/

相关文章:

jquery - 等待 getJSON 响应

java - 推迟 thenApplyAsync 执行

javascript - Jquery事件被多次调用

javascript - 表格上的双水平滚动 - JQuery

javascript - 确保 <section> 高度与重新刷新时的视口(viewport)高度匹配

javascript - 通过 AJAX/jQuery 将特定值从数据库写入 HTML

javascript - $.clone 与 ajax XHR 请求会中断事件吗?

java - Android Studio,R报错,无法解决

java - Maven 通过 MAVEN_OPTS 指定设置文件位置

java - 绘制动态图(正交)