Ajax.jsp代码
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!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=utf-8">
<title>Ajax</title>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlrequest;
if(window.XMLHttpRequest){
xmlrequest = new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
xmlrequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlrequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
}
}
}
//创建json对象
//JSON 值可以是:
//数字(整数或浮点数)
//字符串(在双引号中)
//逻辑值(true 或 false)
//数组(在方括号中)
//对象(在花括号中)
//null
var json ={"name":"張三","password":"123"}
//将json数据转换成字符串方便传递
var account=JSON.stringify(json);
xmlrequest.open("POSt",'http://localhost:8080/showUsers/Ajax?account='+account+'',true);
//设置请求头
//发送请求
xmlrequest.send(account);
xmlrequest.onreadystatechange = function processResponse(){
//响应完成
if(xmlrequest.readyState == 4){
//响应正常
if(xmlrequest.status == 200){
//接收json字符串
var head = xmlrequest.responseText;
//将字符串转化成json数据格式
var json1=JSON.parse(head);
//调用json数据中属性
alert(json1.password);
}
}
};
}
</script>
</head>
<body>
<div id="myDiv"><h3>Let AJAX change this text</h3></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
<%=request.getParameter("account") %>
</body>
</html>
Ajax.java代码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Object account = request.getAttribute("account");
String account=request.getParameter("account");
System.out.println(account);
response.setContentType("text/html;charset=UTF-8");
request.setAttribute("account", account);
PrintWriter writer = response.getWriter();
writer.write(account);
writer.flush();
writer.close();
}