背景
AJAX:Asynchronous JavaSpript and XML。在2005年2月由Jesse James Garrett首次提出,在google地图首次被应用后广为人知,成为目前主流的开发模式,优点是避免网页频繁刷新造成的不良用户体验,减少服务器的执行压力,提高服务器程序的共用行。
原理
使用ajax与服务器交互时,发送以及接收的信息是特殊数据格式,而非整个网页程序,因此不需要刷新。
实例代码(html内嵌js)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax实例(读取json文件)</title>
<script type="text/javascript">
function getXHR(){
if(window.XMLHttpRequest){
return new window.XMLHttpRequest()
}else{
//解决微软的特殊情况,基本可以不写(因为除微软外的浏览器都支持上面的哪个)
return new window.ActiveXObject('microsoft.xmlhttp')
}
}
//异步请求服务器数据函数
function jsonData(){
//var进行局部化,避免冲突
var xhr = getXHR()
xhr.open('GET','data.json')//三个参数:请求、url、是否异步(默认异步)
xhr.send(null)
//监听程序
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status == 200){
//请求结束并且返回正常页面
//得到服务器返回的json字符串
resp = xhr.responseText
//console.log(resp)
htmlText = ""
//解析字符串还原为json对象
jsonobj = JSON.parse(resp) //变量名与函数名不要相同
//console.log(jsonobj)
//组织显示html格式
htmlText = "<tr><td>" + jsonobj.user + "</td><tr>" //严格按照html格式
document.getElementById('userData').innerHTML = htmlText //注意大小写,前后保持一致
//另一种方法
//setInnerHTML('userData',htmlText)
}
}
}
/*function setInnerHTML(id,text){
document.getElementById(id).innerHTML = test
}*/
</script>
</head>
<body>
<input type="button" value="加载" onclick="jsonData()"/>
<table border="1">
<thead>
<tr><th>用户名</th></tr>
</thead>
<tbody id="userData"></tbody>
</table>
</body>
</html>
结果截图
初始:
点击‘加载’后:
传说中的Ajax…以上