我正在使用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", "[email protected]");
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", "[email protected]");
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
gcalex5 - 其相關的下拉菜單。而且這兩個都不應該通過JSON動作填充,只有應該通過JSON填充的子級下拉列表。 – vipin
我會推薦使用'sj:select'標籤,然後使用和onChangeTopics選項來讓另一個依賴另一個,然後給孩子一個和href標籤到你的json標籤。當然,如果你可以使用struts2 jquery插件和struts2 json插件。如果你想我可以給你和我的代碼摘錄 – gcalex5