Ajax基本用法

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax4</title>
</head>
<body>
  <div id="box"></div>
  <input type="button" value="请求数据" id="btn">
</body>
<script>
  var box=document.getElementById('box');
  var btn=document.getElementById('btn');

  btn.onclick=function() {
  // 1.创建.XMLHttpRequest对象
  if (window.XMLHttpRequest) {
    var xhr=new XMLHttpRequest();
  }else{
    var xhr=new ActiveXObject('Microsoft.XMLHTTP')
  };
  // 2.创建与服务器的链接
  xhr.open('GET','http://localhost/ajax/test1.json?t='+new   Date().getTime(),true);
  // 3.发送请求
  xhr.send(null);
  xhr.onreadystatechange=function() {
  // alert(xhr.readyState);
  if (xhr.readyState==4) {//服务器准备就绪
  if (xhr.status==200) {//数据返回成功
  var json=xhr.responseText;
  var jsons=eval('('+json+')');
  // alert(jsons.title.length);
  var text='';
  for (var i = 0; i < jsons.title.length; i++) {
    text+=jsons.title[i]+'作者:'+jsons.author[i]+'</br>';
  };
    box.innerHTML=text;
  }else{
    alert(xhr.status);
  }
  };
};
};
</script>
</html>

 

大毛流浪记3作者:老猫1出版日期:2001
二毛流浪记3作者:老猫2出版日期:2002
三毛流浪记3作者:老猫3出版日期:2003
四毛流浪记3作者:老猫4出版日期:2004

posted @ 2016-06-30 15:52  FallenLunatic  阅读(123)  评论(0编辑  收藏  举报