在学习SpringMVC的过程中,接触到ajax,顺便复习一下前面学习到的知识!
这篇博客中讲的比较详细 http://www.cnblogs.com/lsnproj/archive/2012/02/07/2340395.html 大家可以参考,我就写一些他没讲到的
一.一个基本例子 无刷新添加数据
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function onClickAjax()
{
var xmlHttp;
//分浏览器创建xmlHttp对象
if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//设置请求类型
xmlHttp.open("POST","/ajaxTest/user/ajaxTest/",true);
//回调函数
xmlHttp.onreadystatechange=function()
{
// alert(xmlHttp.readyState);
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
var data=xmlHttp.responseText;
document.getElementById('div1').innerHTML=data;
alert(data);
}
else
alert(xmlHttp.status);
}
}
xmlHttp.send();
}
function test(){alert(" no problem");}
</script>
</head>
<body>
<form>
<input οnclick="test()" type="button" value="test"/>
<input οnclick="onClickAjax()" type="button" value="submit"/>
<div id="div1">
</div>
</form>
</body>
</html>
后台代码
@RequestMapping("/ajaxTest")
public String ajaxTest(HttpServletRequest request,HttpServletResponse response)
{
String temp=(String)request.getAttribute("msg");
System.out.println(temp);
try {
/*放回json类型的数据
* response.setContentType("application/json");
* String str="{\"age\":\"12\"}";
*/
StringBuilder sb=new StringBuilder();
sb.append("<ul>");
sb.append("<li>jackvin");
sb.append("</li>");
sb.append("<li>tom");
sb.append("</li>");
sb.append("</ul>");
String str=sb.toString();
response.getWriter().write(str);
response.getWriter().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "/showView"; //ajaxTest
}
spring配置我就不贴了,结果是我们看到在原先没有任何数据的页面上,会多出两行数据,这就是ajax的无刷新功能,我们可以用它来添加评论等等
二.很多时候我们需要通过ajax传递json数据 ,那该怎么办呢?