struts2:使用 javascript 和 jquery 根据第一个选择值更新第二个选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7005056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:39:51  来源:igfitidea点击:

struts2: update second select based on first select value using javascript and jquery

javascriptjqueryselectstruts2

提问by Johnny

I am working on a struts2 project where I have 3 html select controls each one being dependent on the previous selection. Say the first select is for country, second for state, third for city. The list of options in the state select would be filtered to only display the states in that country and so on. Due to some other limitations I am using the basic html select control instead of struts2's. Here is a sample of how I am currently populating the select:

我正在处理一个 struts2 项目,其中我有 3 个 html 选择控件,每个控件都依赖于先前的选择。假设第一个选择是国家,第二个是州,第三个是城市。州选择中的选项列表将被过滤以仅显示该国家/地区的州等。由于其他一些限制,我使用的是基本的 html 选择控件而不是 struts2 的。这是我目前如何填充选择的示例:

<select id="stateSelect"  name="selectedState">
<s:iterator value="#session['myModel'].states" status="itr">
     <option value="<s:property value="code"/>">
      <s:property value="label"/>
</option>
</s:iterator>
</select>

I think that what I need to do is onchange event do an ajax call to retrieve the list of "states" based on the selected "country". The questions are:
1. how can I do this ajax call using jquery?
2. what do I need to pass as the url for the ajax call? just the action name?
3. how can I parse the results back? From java code I can return a list of "State" objects that have "code" and "label" and other properties. How can I parse this list in javascript and generate the proper options for the select tag?

我认为我需要做的是 onchange 事件执行 ajax 调用以检索基于所选“国家/地区”的“状态”列表。问题是:
1. 我怎样才能使用 jquery 进行这个 ajax 调用?
2. 我需要传递什么作为 ajax 调用的 url?只是动作名称?
3. 如何解析结果?从 Java 代码中,我可以返回具有“代码”和“标签”和其他属性的“状态”对象列表。如何在 javascript 中解析此列表并为 select 标记生成正确的选项?

采纳答案by anupam

<select id="stateSelect"  name="selectedState" onchange="loadCities(this.value)">
<s:iterator value="#session['myModel'].states" status="itr">
     <option value="<s:property value="code"/>">
      <s:property value="label"/>
</option>
</s:iterator>
</select>

<select id="citySelect"  name="selectedCity" >
</select>

JQuery

查询

function loadCities(value){

        $("#citySelect").get(0).options.length = 0;
        $("#citySelect").get(0).options[0] = new Option("Loading cities", "-1"); 

        $.ajax({
            type: "POST",
            url: "MyStrutsActionToGetCities",
            data: "{stateID:" + value+ "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#citySelect").get(0).options.length = 0;
                $("#citySelect").get(0).options[0] = new Option("Select city", "-1"); 

                $.each(msg.d, function(index, item) {
                    $("#citySelect").get(0).options[$("#citySelect").get(0).options.length] = new Option(item.Display, item.Value);
                });
            },
            error: function() {
                $("#citySelect").get(0).options.length = 0;
                alert("Failed to load cities");
            }
        });
}

Taken from this tutorial

取自本教程

Update:This example is used to load city list based on the state selected. You can do similar thing to load state list on country selection. Also here is a linkdescribing ajax request/response for struts without using any plugin

更新:此示例用于根据所选州加载城市列表。你可以做类似的事情来加载国家选择的州列表。还这里是一个链接描述用于支柱AJAX的请求/响应,而无需使用任何插件

回答by jonathan.cone

Generally, the way to do this is using the Struts2 JSON pluginwhich ships with recent versions of Struts2. To interact with jQuery in your JSP you'll want to use s:url to create a URL for your JSON action and then you can invoke it using jQuery's .getJSON()or .load().

通常,执行此操作的方法是使用Struts2 JSON 插件,该插件随最新版本的 Struts2 一起提供。要在您的 JSP 中与 jQuery 交互,您需要使用 s:url 为您的 JSON 操作创建一个 URL,然后您可以使用 jQuery 的.getJSON().load()调用它。

However, if your dropdown choices really aren't that complicated, don't over-architect. It can be easier to render them all using s:iterator on the initial page load and use .change()on your dropdown boxes to either move the data between select components, or augment the name attribute on one of the select boxes for the form submit.

但是,如果您的下拉选项真的没有那么复杂,请不要过度设计。在初始页面加载时使用 s:iterator 渲染它们会更容易,并在下拉框中使用.change()在选择组件之间移动数据,或增加表单选择框之一上的 name 属性提交。