ajax 简单例子
Html 代码:
<html> <body> <div id="myDiv"><h3>Let AJAX change this text</h3></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
js代码:
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc() {
//ajax script goes here...
if(window.XMLHttpRequest) {
//code for IE7+, firefox, Chrome, Opera,Sarari
xmlhttp = new XMLHttpRequest();
}else {
//code for IE6,IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp != null) {
//创建响应XMLHttpRequest对象状态变化的函数
xmlhttp.onreadystatechange = httpStateChange;
//创建http请求
xmlhttp.open('GET', 'json/data.json', true);
//发送http请求
xmlhttp.send(null);
}
}
function httpStateChange() {
console.log(xmlhttp.readyState, xmlhttp.status);
//请求中.
if(xmlhttp.readyState == 1) {
//loading..
document.getElementById('myDiv').innerHTML = 'loading..';
}
////异步调用完毕
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
console.log(data);
document.getElementById('myDiv').innerHTML = data.sites[1].Name;
}
}
</script>

浙公网安备 33010602011771号