前台页面:一个ajax一般有3个function
<script type="text/javascript">
var xmlhttp;
//创建xmlhtt对象
function createHttpXmlHttp(){
if(window.ActiveXObject){
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}else{
xmlhttp = new XMLHttpRequest();
}
}
//发出ajax请求
function startRquest(){
createHttpXmlHttp();
try {
xmlhttp.onreadystatechange = handlestatechange;
xmlhttp.open("get","ajax.do?action=getInfo",true);
xmlhttp.send(null);
} catch (e) {
alert("xmlhttp fail");
}
}
//回调函数
function handlestatechange(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200||xmlhttp.status==0){
try {
var result = xmlhttp.responseText;
var data = eval(result);
alert(data[3]);
} catch (e) {
alert(e.message);
}
}
}
}
</script>
后台要把数据封装成json格式,如果数据从db中,则需要json的jar包。本例把从一个本地文件A.java中获取数据:
public class AjaxT extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String method = req.getParameter("action");
if(method.equals("getInfo")){
getInfo(req, resp);
}
}
protected void getInfo(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setCharacterEncoding("GBK");
PrintWriter out = resp.getWriter();
StringBuffer sb = new StringBuffer();
String path = "F:/A.java";
try {
InputStream in = new FileInputStream(new File(path));
byte[] temp = new byte[1024];
int k=0;
while((k=in.read(temp))!=-1){
sb.append(new String(temp,0,k));
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
out.write(sb.toString());
System.out.println("AAAAAAAA");
}
}
A.java中数据格式为:[{"name":"huazi"},{"name":"kobe"},"hello",78]