今天采用原生的Ajax方式获取JSON格式结果的例子,一个简单的Web项目,没有什么工具,采用IIS发布的,步骤如下:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/index.css">
<script type="text/javascript" src="js/index.js"></script>
</head>
<body id="tableContainer" onload="ajaxRequest()">
<table border="1" width="500px;">
<tr><td>Name</td></tr>
</table>
</body>
</html>
var xmlHttpRequest = null;
function ajaxRequest() {
if (window.ActiveXObject) // IE浏览器
{
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) // 除IE以外的其他浏览器
{
xmlHttpRequest = new XMLHttpRequest();
}
if (null != xmlHttpRequest) {
/*
* POST方式向服务器发出一个请求
*/
xmlHttpRequest.open("GET","/data/data.html",true);
xmlHttpRequest.onreadystatechange = ajaxCallBack;
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send();
}
}
function ajaxCallBack() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
var content = xmlHttpRequest.responseText;
var mList = eval(content);
var tabObj = document.getElementById('tableContainer');
var m = '';
for (var i = 0; i < mList.length; i++) {
var obj = mList[0];
var name = obj.name;
var text = obj.text;
m += '<tr width="100%"><td ><table border="1" width="100%"><tr><td style="width:90%;" class="head">' + name + '</td><td rowspan="2" style="cursor:pointer;">222</td></tr><tr><td class="name">'+text+'</td></tr></table></td></tr>';
}
tabObj.lastChild.prevIoUsSibling.innerHTML+=m;
}
}
}
3. Ajax加载数据格式
[{name:'aaaa',text:'22222'},{name:'bbbb',text:'33333'}]
4. CSS文件
.head { position: relative; left:25px; font-size: 18pt; font:italic arial,sans-serif; color:gray; z-index: -1; } .name{ position: relative; left:25px; font-size: 8pt; font:italic arial,sans-serif; color:gray; }