Ajax与Servlet之间的数据传递
Jquery Ajax向Servlet发送数据
- 第一步:导入Jquery文件,Jquery.js并导入json的jar包(这里使用谷歌的gson.jar包)
- 第二步:在页面写Ajax代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="jq/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
$.ajax({
url:'formServlet',
type:'post',
dataType:'json',
data:$("#myForm").serialize(),//使用form表单提交数据时,可使用表单序列化方法serialize()
success:function(data){
//回调函数
for(var i=0;i<data.length;i++){
//向body中添加p元素
$("body").append($("<p>"+data[i]+"</p>"));
}
}
});
});
});
</script>
</head>
<body>
<form id="myForm" action="">
<input id="p1" name="p1" >
<input id="p2" name="p2" >
<input id="btn" type="button" value="提交"/>
</form>
</body>
</html>
3.Servlet代码:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("application/json;charset=utf-8"); // 设置返回的数据类型和编码
String p1 = request.getParameter("p1"); // 获取参数
String p2 = request.getParameter("p2"); // 获取参数
Gson gson = new Gson(); // 使用gson,创建对象
List list = new ArrayList();
list.add(p1); //添加数据
list.add(p2);
String json = gson.toJson(list); // 把list集合转换为json传输
response.getWriter().append(json); // 返回数据
}
结果展示
原生Ajax向Servlet发送数据
- 页面代码
<button onclick="chang()">hello world</button>
<script>
function chang(){ //点击事件
var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象
xhr.open("post","EmpServlet",true); //open()方法中的三个参数分别代表请求类型,请求地址,是否异步传输,默认为true
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//如果为post请求,则必须设置请求头
xhr.send("aa=ajax"); //send()方法里面为传输的参数send("name=张三&sex=男")中间用&分开
xhr.onreadystatechange=function(){ //回调函数
if(xhr.readyState===4&&xhr.status===200){ //readyState===4代表 请求已完成,且响应已就绪,status===200表示OK
alert(xhr.responseText); //responseText代表相应的参数
}
}
}
</script>
- Servlet代码
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8"); //设置返回的数据类型和编码
String aa = request.getParameter("aa"); //获得参数
if ("ajax".equals(aa)) { //判断获得的aa是否是ajax
response.getWriter().println("你好,Ajax!"); //如果是,返回数据
}
}
结果展示