最近写一个数据收集平台,在页面与服务器之间传递数据,需要用到ajax技术,这里写一下如何使用ajax,将json数据放入动态生成的表格中。
1.在页面添加<script type="text/javascript">
ajax代码;
</script>
2.ajax代码
ajax实现页面与服务器数据的传递,是靠XMLHttpRequest类的对象实现的,
首先,获得XMLHttpRequest的对象
定义一个全局变量,存放XMLHttpRequest的对象
var xmlHttp;
function getXMLHttpRequest(){
var xmlHttp;
//如果于浏览器兼容,创建XHR的对象,并返回该对象
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
if(window.AxtiveXObject){
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
if(!xmlHttp){
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlHttp;
}
3.ajax代码
写一个函数,调用XMLHttpRequest对象,向服务器发送请求,获得返回的json数据
function getJsonDatas(){
//获得xmlHttp对象
xmlHttp = getXMLHttpRequest();
var url="TestServlet"; //目标servlet在web.xml中配置的路径
xmlHttp.open("POST",url,true);
//绑定回调方法,接收json数据
xmlHttp.onreadystatechange=callback;//回调函数callback(),
xmlHttp.send();
}
4.ajax代码
回调方法
function callback(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
//获取服务器返回的文本数据
var result = xmlHttp.responseText;
//解析获得的json数据
var json = eval("("+result+")");
//创建dealJson()函数,处理解析后的json数据
dealJsonData(json);
}
}
}
5.ajax代码
处理json数据的函数
function dealJsonData(jsonData){
//定时更新表格数据时需要用到,清空之前的数据
clearContent();
//获取数据长度,
var size=getHsonLength(jsonData);
//如果json数据为非键值对的形式,可以用var nextNode =jsonData[i]来接收数据
//如果json数据为键值对的形式
var jsondata = jsonData;
for(var i=0;i<size;i++){
var nextNode = jsondata[i];
//将每一组数据存入数组中
var str = new Array(nextNode.id , nextNode.username , nextNode.password);
//将数据存入生成的表格中
createTable(str);
}
}
6.ajax代码
//获得json的长度,json数据不能通过length获得长度,需要对其遍历计算其长度
function getHsonLength(json){
var jsonLength=0;
for (var i in json) {
jsonLength++;
}
return jsonLength;
}
7.ajax代码
动态生成表格
createTablr(){
var tr=document.createElement("tr"); tr.onmouseover=function(){ this.className="mouseOver"; }; tr.onmouseout=function(){ this.className=""; }; tr.onclick=function(){ }; for(var j=0;j<10;j++){ var td=document.createElement("td"); td.setAttribute("border","1px"); td.setAttribute("bgcolor","#FFFAFA"); td.setAttribute("bgcolor","#FFFAFA"); td.setAttribute("align","center"); td.setAttribute("width","10%"); td.appendChild(document.createTextNode(str[j])); tr.appendChild(td); } document.getElementById("product_info_table").appendChild(tr);
}
8.ajax代码
//定时更新表格数据时需要用到,清空之前的数据
function clearContent(){
var contentTableBody=document.getElementById("product_info_table");
var size=contentTableBody.childNodes.length;
for(var i=size-1;i>=0;i--){
contentTableBody.removeChild(contentTableBody.childNodes[i]);
}
}
9.显示表格的JSP页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
ajax代码;
</script>
</head>
<body>
<div id="mydiv">
<div id="real_time"><!-- 实时监测 rules使表格线可见-->
<table id="product_info" bgcolor="#FFFAFA" border="1px" rules="all" cellspacing="0" cellpadding="0" width="100%">
<tbody id="product_info_table" width="100%" >
<!-- 放置动态生成的表格的行和列
-->
</tbody>
</table>
</div>
</div>
</body>
</html>
10. servlet 数据发送
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException{
request.setCharacterEncoding("utf-8");//设置编码格式
response.setCharacterEncoding("utf-8");//设置编码格式
Map<String,String> map = null;;
List<Map> lis =new ArrayList<Map>();
try {
jsonArray = new JSONArray();
for(int i = 0; i < list.size(); i++)
{
map = new HashMap<String,String>();
map.put("id", "0001");
map.put("username", "zhangsan");
map.put("password", "123456");
lis.add(map);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.getWriter().write(jsonArray.fromObject(lis).toString());
}
注:原生ajax的使用在浏览器中存在不兼容的情况,建议使用jQuery框架