http://zy116494718.iteye.com/blog/786025
Ajax和iframe都可以實現局部刷新。他們實現的功能基本一樣。
下面是一個用jquery實現的Ajax局部刷新。
實現的功能是在文本框中輸入年齡后,在下面的<div>中顯示出數據庫中該年齡的所有用戶姓名
ajaxshuaxin.jsp:
<script type="text/javascript">
$(function(){
$("input:eq(1)").click(function(){
$("#show").html("");
$.ajax({
type:"POST", //請求方式
url:"ajaxshuaxin.do", //請求路徑
cache: false, //(默認: true,dataType為script和jsonp時默認為false) jQuery 1.2 新功能,設置為 false 將不緩存此頁面。
data:"age="+$("input:eq(0)").val(), //傳參
dataType: "html", //返回值類型 使用json的話也可以,但是需要在JS中編寫迭代的html代碼,如果格式樣式
success:function(data){ 復雜的話還是用html返回類型好
$("#show").html(data);
}
});
})
})
</script>
年齡:<input type="text" name="age">
<input type= "button" name="submit" value="查詢">
<p>姓名 年齡</p>
<div id="show"></div>
ajaxShuaXin.java:
String age = req.getParameter("age");
List list = helpService.getList(age); //通過age查詢數據庫中的數據
HashMap map = new HashMap();
map.put("list", list);
return new ModelAndView(getResultPage(),map); //getResultPage()是shuaxin.jsp
shuaxin.jsp:
<c:forEach var="str" items="${list}">
<p>${str.name} ${str.age}</p>
</c:forEach>