为啥我的第二个下拉菜单没有被填充?

Posted

技术标签:

【中文标题】为啥我的第二个下拉菜单没有被填充?【英文标题】:Why is my second dropdown menu not getting populated?为什么我的第二个下拉菜单没有被填充? 【发布时间】:2014-08-08 06:16:32 【问题描述】:

我正在使用 JSP、STRUTS2、AJAX、jQuery 和 mysql 来填充相关下拉列表。我想知道为什么我的第二个下拉列表没有被填充?请让我知道我在这里缺少什么。

AjaxJsonAction.java

package com.action;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;


import com.opensymphony.xwork2.Action;
public class AjaxJsonAction implements Action

    private Map<String, String> stateMap = new LinkedHashMap<String, String>();
    private String dummyMsg;
    //Parameter for Jquery
    private String countryName;
    private String eventName;
//
//  private Map<String, String> eventList = new LinkedHashMap<String, String>();
//  private Map<String, String> eventDateList = new LinkedHashMap<String, String>();
    private ArrayList<Event> eventList;
    private ArrayList<EventShow> eventShowList;
    private Map<String, String> edList = new LinkedHashMap<String, String>();

    public Map<String, String> getStateMap() 
        return stateMap;
    

    public String getDummyMsg() 
        return dummyMsg;
    

    public String getCountryName() 
        return countryName;
    


    public void setStateMap(Map<String, String> stateMap) 
        this.stateMap = stateMap;
    

    public void setDummyMsg(String dummyMsg) 
        this.dummyMsg = dummyMsg;
    

    public void setCountryName(String countryName) 
        this.countryName = countryName;
    

//  public Map<String, String> getEventList() 
//      return eventList;
//  
//  public void setEventList(Map<String, String> eventList) 
//      this.eventList = eventList;
//  
//  
//  public Map<String, String> getEventDateList() 
//      return eventDateList;
//  
//  public void setEventDateList(Map<String, String> eventDateList) 
//      this.eventDateList = eventDateList;
//  
    public String getEventName() 
        return eventName;
    

    public void setEventName(String eventName) 
        this.eventName = eventName;
    
    public ArrayList<Event> getEventList() 
        return eventList;
    

    public void setEventList(ArrayList<Event> eventList) 
        this.eventList = eventList;
    

    public ArrayList<EventShow> getEventShowList() 
        return eventShowList;
    

    public void setEventShowList(ArrayList<EventShow> eventShowList) 
        this.eventShowList = eventShowList;
    

public Map<String, String> getedList() 
    return edList;

public void setedList(Map<String, String> edList) 
    this.edList = edList;



private List<EventShow> eventShows;

public List<EventShow> getEventShows()  return eventShows; 

    public String execute() 

//      dummyMsg = "Ajax action Triggered";
//      return SUCCESS;
        System.out.println("inside execute.");
        populateEvent();
         System.out.println("eventList Count="+eventList.size());
//      populateShow(eventName);
        return "success";
    

    public void populateEvent() 
        System.out.println("inside populateEvent.");
        Connection conn = null;

          try 
             String URL = "jdbc:mysql://localhost:3306/bookmyshow_dates";
             Class.forName("com.mysql.jdbc.Driver");
             conn = DriverManager.getConnection(URL, "dra2", "dr@2");
             String sql = "SELECT DISTINCT * FROM EVENTS";
//           String sql ="SELECT * FROM user3333";
         PreparedStatement ps = conn.prepareStatement(sql);

             ResultSet rs = ps.executeQuery();

             eventList = new ArrayList<Event>();
             while (rs.next()) 
//               eventList.put(rs.getString("EventId"),rs.getString("EventName"));
                 eventList.add(new Event(rs.getInt("EventId"),rs.getString("EventName")));
             
           catch (Exception e) 
//            return "error";
           
          finally 
             if (conn != null) 
                try 
                   conn.close();
                 catch (Exception e) 
                
             
          
          System.out.println("inside populateEvent End.");

//        return "getEventList";
    

//  public void populateShow(String eventName) 
//  public ArrayList<EventShow> populateShow() 
//  public Map<String, String> populateShow() 
    public void populateShow() 
        String eventId="1";
        System.out.println("parameter:"+eventId);
        Connection conn = null;

          try 
             String URL = "jdbc:mysql://localhost:3306/bookmyshow_dates";
             Class.forName("com.mysql.jdbc.Driver");
             conn = DriverManager.getConnection(URL, "dra2", "dr@2");


             String sql="SELECT ShowId,EventDate,\r\n" + 
                    "CASE \r\n" + 
                    "   WHEN DATEDIFF(EventDate,NOW()) = 0 THEN CONCAT('Today',', ',DAY(EventDate),' ',MONTHNAME(EventDate))\r\n" + 
                    "   WHEN DATEDIFF(EventDate,NOW()) = 1 THEN CONCAT('Tomorrow',', ',DAY(EventDate),' ',MONTHNAME(EventDate))\r\n" + 
                    "   WHEN DATEDIFF(EventDate,NOW()) > 1 THEN CONCAT(DAYNAME(EventDate),', ',DAY(EventDate),' ',MONTHNAME(EventDate))\r\n" + 
                    "END AS EventDay\r\n" + 
                    ",es.EventId\r\n" + 
                    "FROM EventShows es\r\n" + 
                    "INNER JOIN EVENTS e ON es.EventId = e.EventId AND (EventDate>=NOW())\r\n" + 
                    "WHERE e.EventId='"+eventId+" ';";
//           String sql ="SELECT * FROM user3333";
         PreparedStatement ps = conn.prepareStatement(sql);

             ResultSet rs = ps.executeQuery();

             eventShowList = new ArrayList<EventShow>();
             while (rs.next()) 
                 eventShowList.add(new EventShow(rs.getInt("ShowId"),rs.getString("EventDay"),rs.getInt("EventId")));
//               eventDateList.put(rs.getString("EventId"), rs.getString("EventName"));
                 edList.put(rs.getString("EventId"), rs.getString("EventName"));
             
           catch (Exception e) 
//            return "error";
           
          finally 
             if (conn != null) 
                try 
                   conn.close();
                 catch (Exception e) 
                
             
          
System.out.println("eventShowList:"+eventShowList.size());
//      JSONArray jsArray = new JSONArray(eventShowList);

        // Converts JSON string into a List of Product object
//      List<EventShow> eventShows = ((List<EventShow>) eventShowList);
//       return eventShowList;
    


Event.java

package com.action;

public class Event 
    private int eventId;

    private String eventName;

    Event(int eventId, String eventName)
    
        this.eventId = eventId;
        this.eventName = eventName;
    

    public int getEventId() 
        return eventId;
    
    public void setEventId(int eventId) 
        this.eventId = eventId;
    
    public String getEventName() 
        return eventName;
    
    public void setEventName(String eventName) 
        this.eventName = eventName;
    


EventShow.java

package com.action;

public class EventShow 

    private int showId;
    private String eventDate;
    private int eventId;

    EventShow(int showId, String eventDate, int eventId)
    
        this.showId = showId;
        this.eventId = eventId;
        this.eventDate = eventDate;
    

    public int getshowId() 
        return showId;
    

    public void setShowId(int showId) 
        this.showId = showId;
    
    public String getEventDate() 
        return eventDate;
    

    public void setEventDate(String eventDate) 
        this.eventDate = eventDate;
    
    public int getEventId() 
        return eventId;
    
    public void setEventId(int eventId) 
        this.eventId = eventId;
    


struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="json-default">

    <action name="getEvents" class="com.action.AjaxJsonAction" >
        <result name="success">/index.jsp</result>
        <result name="error">/error.jsp</result>
    </action>

    <action name="populateEventDate" class="com.action.AjaxJsonAction" method="populateShow">
<!--        <result type="json">/index.jsp</result> -->
            <result name="success">/index.jsp</result>
    </action>

</package>
</struts>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Struts2</display-name>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

index.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>AJAX in Struts 2 using JSON and jQuery</title>
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script>
$(document).ready(function() 
    $('#country').change(function(event) 
        var country = $("select#country").val();
        $.getJSON('ajaxAction', 
            countryName : country
        , function(jsonResponse) 
            $('#ajaxResponse').text(jsonResponse.dummyMsg);
            var select = $('#states');
            select.find('option').remove();
            $.each(jsonResponse.stateMap, function(key, value) 
                $('<option>').val(key).text(value).appendTo(select);
            );
        );
    );

//  $('#event').change(function(event) 
//      var country = $("select#event").val();
// //       $.getJSON('<s:url action='populateEventDate'/>', 
//  $.getJSON('populateEventDate', 
//          eventName : country
//      , function(jsonResponse) 
//          $('#ajaxResponse').text(jsonResponse.dummyMsg);
//          var select = $('#eventDate');
//          select.find('option').remove();
//          $.each(jsonResponse.eventDateList, function(key, value) 
//              $('<option>').val(key).text(value).appendTo(select);
//          );
//      );
// //        $.ajax(
// //               type: "POST",
// //               url: "<s:url action='populateEventDate'/>",
// //               data: 'eventName': country,
// //                contentType: "application/json; charset=utf-8",
// //               dataType: "json",
// //               success: function(msg) 
// //                   $("#eventDate").get(0).options.length = 0;
// //                   $("#eventDate").get(0).options[0] = new Option("Select event", "-1"); 

// //                   $.each(msg.d, function(index, item) 
// //                       $("#eventDate").get(0).options[$("#eventDate").get(0).options.length] = new Option(item.Display, item.Value);
// //                   );
// //               ,
// //               error: function(meg) 
// //                   $("#eventDate").get(0).options.length = 0;
// //                   alert("Failed to load events."+meg);
// //               
// //           );
//  );

$('#event').change(function(event) 
        var eName = $("select#event").val();
//      $.getJSON('populateEventDate', 
//          eventName : eName
//      , function(jsonResponse) 
//          $('#ajaxResponse').text(jsonResponse.dummyMsg);
//          var select = $('#eventDate');
//          select.find('option').remove();
//          $.each(jsonResponse.stateMap, function(key, value) 
//              $('<option>').val(key).text(value).appendTo(select);
//          );
//      );

        $.ajax(
            type:'POST',
            dataType:'json',
//          url:'populateEventDate?eventName='+eName,
        url: "<s:url action='populateEventDate'/>",
        data: 'eventName': eName,
//         dataType: "text",
        contentType: "application/json; charset=utf-8",

            success: function(jsonResponse) 
                $('#ajaxResponse').text(jsonResponse.dummyMsg);
                var select = $('#eventDate');
                select.find('option').remove();
                $.each(jsonResponse.eventDateList, function(key, value) 
                $('<option>').val(key).text(value).appendTo(select);
                );
                                ,
            error: function(jsonResponse) 
                $("#eventDate").get(0).options.length = 0;
                alert("Failed to load events."+jsonResponse);
            
        );
    );
);
</script>
</head>
<body>
    <h3>AJAX calls to Struts 2 using JSON and jQuery</h3>

    <br />
    <br />
    <s:select name="event" id="event" list="eventList" listKey="eventId"
            listValue="eventName" headerKey="0" headerValue="Event"
            label="Select a event" />
    <br />
    <br />
    <s:select id="eventDate" name="eventDate" list="'Select eventdate'"
        label="Select eventdate" />

</body>
</html>

另外,我在函数中收到 JSON 响应为 NULL:$('#event').change(function(event)

【问题讨论】:

您是否希望其中一个影响另一个的人口?并且都应该通过 JSON 操作填充? gcalex5 - 它的依赖下拉列表。两者都不应该通过 JSON 操作填充,只有子下拉菜单应该通过 JSON 填充。 我建议使用sj:select 标记,然后使用和 onChangeTopics 选项让一个依赖于另一个,然后给孩子一个和 href 标记到您的 json 标记。这当然是你可以使用 struts2 jquery 插件和 struts2 json 插件。如果你愿意,我可以给你并摘录我的代码 是的,请。赞赏。让我看看你的代码。 【参考方案1】:

你需要做一些更正。

第 1 步:struts.xml 文件中

<action name="populateEventDate" class="com.action.AjaxJsonAction" method="populateShow">
  <result type="json">/index.jsp</result> 
</action>

第2步:AjaxJsonAction.java

public String populateShow() 
    edList.put("1", "Monday");// Fill this map with your database values
    return "success";

第 3 步:index.jsp -> 使用 cdn 中的 jquery js 并使用以下代码

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

<script type="text/javascript">
$(document).ready(function()   
    $('#event').change(function(event) 
        var event = $("select#event").val();

        $.getJSON('populateEventDate', 
            eventName : event
        , function(jsonResponse) 
            $('#ajaxResponse').text(jsonResponse.dummyMsg);
            var select = $('select#eventDate');
            select.find('option').remove();
            $.each(jsonResponse.edList, function(key, value) 
                $('<option>').val(key).text(value).appendTo(select);
            );
        );
    );
);

</script>

如果您遇到任何错误,请回复我。

【讨论】:

【参考方案2】:

感谢帕思的建议。 但是我从您的帖子中得到了这个想法,并且必须修改 struts.xml 以包含以下操作

<action name="getEvents" class="qBook.AjaxJsonAction" >
        <result name="success">/index.jsp</result>
    </action>
    <action name="ajaxAction" class="qBook.AjaxJsonAction" method="TestABC">
        <result type="json">/index.jsp</result>
    </action>

第一个动作 - 在页面加载时获取第一个下拉列表的数据,第二个动作在 AJAX 调用的帮助下获取基于数据的第一个下拉选择值。您的评论对我很有帮助,再次感谢您。

【讨论】:

以上是关于为啥我的第二个下拉菜单没有被填充?的主要内容,如果未能解决你的问题,请参考以下文章

第一个下拉菜单更改第二个下拉菜单相关项目显示

根据第一个选择动态填充第二个下拉菜单

根据第一个和第二个菜单选择填充第三个下拉菜单

根据另一个下拉列表中的选择填充一个下拉列表,然后重定向

使用与第一个下拉列表相同的值填充第二个下拉列表

下拉菜单无法正常工作