ajax基础

前台页面:一个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]


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值