日期:2014-05-16  浏览次数:20730 次

struts2+ajax做的一个级联下拉列表
struts2+ajax做的一个级联下拉列表
struts端代码:
/**
* 級聯顯示社群的資訊類別
* @return
*/
public String showNewsType() {
    newsTypeList = associationNewsTypeService.showNewsTypeListByAssnId(associationId);
    return SUCCESS;
}

struts配置文件代码:
<!-- 級聯顯示社群資訊分類 -->
<action name="showNewsType" class="wwwUserGovernmentAction" method="showNewsType">
      <result type="json"></result>
</action>

ajax代码:
/**
*級聯下拉列表顯示
*/
function showNewsType(newsTypeId) {
    var parent = document.getElementById("synAssociationSelect");
    var associationId = parent.options[parent.selectedIndex].value;
if(associationId == 0) {
$("#newsTypeSelectTd").css("display","none");
} else {
var params = {"associationId":associationId};
$.ajax({
type : "post",
url : "/government/showNewsType",
async : false,
data : params,
dataType : "json",
success : function(json) {
var newsTypeSel = document.getElementById("newsTypeSelect");
newsTypeSel.length = 0;
if(json.newsTypeList.length == 0) {
    newsTypeSel.options.add(new Option("該社群沒有資訊分類", 0));
}
for(var i = 0; i < json.newsTypeList.length; i++) {
   if(json.newsTypeList[i].typeId == newsTypeId) {
newsTypeSel.options.add(new Option(json.newsTypeList[i].typeName, json.newsTypeList[i].typeId, 'seleted'));
   } else {
newsTypeSel.options.add(new Option(json.newsTypeList[i].typeName, json.newsTypeList[i].typeId));
   }
}
}
});

    $("#newsTypeSelectTd").css("display","block");
}
}

html代码:
<tr>
                        <td style="vertical-align:top;">同步社群:</td>
                            <td>
                            <select id="synAssociationSelect" name="governmentQuestion.synAssociationId" onchange="showNewsType($!

{governmentQuestion.associationNewsTypeId})">
#if($userAssociationList.size() > 0)
<option value="0">--請選擇--</option>
#foreach($userAssociation in $userAssociationList)
<option value="$!{userAssociation.associationId}" #if($!

{governmentQuestion.synAssociationId} == $!{userAssociation.associationId})selected#end>$!{userAssociation.associationName}</option>
#end
#else
<option value="0">--您還沒有加入社群--</option>
#end
                            </select>
                            </td>
<td id="newsTypeSelectTd" style="display:none" colspan="2">
                            <select id="newsTypeSelect" name="governmentQuestion.associationNewsTypeId">