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

查看:107
本文介绍了在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.

有两个< s:select> s,一个包含在页面加载时加载的国家/地区列表,另一个包含与从国家/地区菜单中选择的国家/地区对应的状态列表。

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:为国家选择>

<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> for state :

<s:select> for state:

<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 映射到动作类中的方法,如下所示。

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

当在菜单中选择国家/地区时,会调用此方法<检索了code> countryId 作为查询字符串参数,但是如何返回/映射此列表, stateTables 来初始化/填充< s:选择> 状态菜单?

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中,这个地图可以写成如下。

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>

< select> 将填充按下给定按钮, btnMap

<select> will be populated on pressing the given button, btnMap.

Struts2怎么样?如何根据另一个< s:select> 填充< s:select>

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基于另一个选择菜单填充一个选择菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆