Jquery +json 異步二級聯動

前提是您已經打好框架



頁面部分:



<script>

$(document).ready(function(){
$("#p_Kind_parent_id1").change(function(){
//alert($("#p_Kind_kind_name").val());
// alert($(this).children('option:selected').val());
$.ajax( {
url : 'kind.kind1.do',
type:"POST",
data: {m:"getJson",parent_id:$("#p_Kind_parent_id1").children('option:selected').val()},
dataType:"json",
success : function(data) {
//清空
$("#p_Kind_parent_id").find("option").remove();
//$("#search").empty();
if(data.result=="empty"){
$("#p_Kind_parent_id").prepend("<option value='0'>請選擇</option>");//爲Select插入一個Option(第一個位置)
}else{

$("#p_Kind_parent_id").prepend("<option value='0'>請選擇</option>");//爲Select插入一個Option(第一個位置)

$.each(data, function(index, content){
$("#p_Kind_parent_id").append("<option value='"+content.id+"'>"+content.kind_name+"</option>");//爲Select追加一個Option(下拉項)
// $("#select_id").prepend("<option value='0'>請選擇</option>");//爲Select插入一個Option(第一個位置)
});



}
},
error : function(data) {
alert("請求超時!")
}
})


});

})

</script>



<tr>
<td width="20%" class="trtwocenter">父類別</td>
<td width="30%" class="troneleft">
<select name="p_Kind_parent_id1" id="p_Kind_parent_id1">
<option value="-1">請選擇</option>
<c:forEach var="each" items="${oneRank}" varStatus="var">
<option value="${each.id}">${each.kind_name}</option>
</c:forEach>
</select>
<select name="p_Kind_parent_id" id="p_Kind_parent_id">
<option value="0">請選擇</option>
</select>
</td>
<td width="20%" class="trtwocenter">類別名稱</td>
<td width="30%" class="troneleft"><input type="text" name="p_Kind_kind_name" maxlength="10" value="${data.kind_name}" id="p_Kind_kind_name"></td>
</tr>



後端







public ModelAndView getJson(HttpServletRequest request, HttpServletResponse response){
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Kind kind = new Kind();
String parent_id=request.getParameter("parent_id");
kind.setParent_id(parent_id);
List list=this.kindService.queryByVO(kind);
// response.setContentType("text/html;kind=utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter pw = null;

// JSONObject jsonObject = new JSONObject();
// jsonObject.put("result", jsonArray);

try {
pw = response.getWriter();
if(list.size()==0){
pw.println("{\"result\":\"empty\"}");
}else{
JSONArray jsonArray = JSONArray.fromObject(list);
pw.write(jsonArray.toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.flush();
pw.close();

return null;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章