例1:在編輯已有內容時通過ajax來對原有內容進行回顯,input以及select
$(".changeShip").click(function(){
$("#get-shipType option").removeAttr("selected"); 在每次點擊時首先對option的屬性進行消除,以免 出現多個selected
var id = $(this).attr("date-exid"); //便獲取對應的id
$.ajax({
type : "POST", //提交方式
url : "<%=request.getContextPath()%>/ship/show/edit/"+id, //傳遞ID進行查詢
cache:false, //不對數據進行緩存
dataType:"json",
success : function(data)
{
$("#get-shipType option[value="+data.shipType+"]").attr("selected","selected"); //對比option的value來給對應的option添加屬性
$("#get-id").val(data.id); //回顯Input內的內容
$("#get-shipNumber").val(data.shipNumber);
$("#get-shipName").val(data.shipName);
}
})
});
例2:通過ajax查詢後臺內容並動態添加元素:
$(".changeShip").click(function()
{
$("#get-shipId").empty(); //每次點擊都消除原先創建的元素 以免多次創建
$.ajax({
type : "GET", //提交方式
url : "<%=request.getContextPath()%>/shipBoat/list/shipNumber",
cache:false,
success : function(data)
{
if(data!=null) //如果查詢內容非空
{
$.each(data,function(ind(索引值 0開始),dd(查詢返回的對象))
{
$("#get-shipId").append("<option value ='"+dd.id+"'>"+dd.shipName+"</option>");//調用返回 對象內的內容進行創建
});
}else
{
//TODO
}
}
})