AJAX基础 -- 笔记 - 图2review0617-4

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>AJAX测试</title>
  6. </head>
  7. <body>
  8. <input type="button" id="btnLoad" value="加载">
  9. <div id="divContent"></div>
  10. </body>
  11. <script type="text/javascript">
  12. document.getElementById('btnLoad').onclick = function(){
  13. // 1、创建xmlhttprequest对象
  14. var xmlHttp;
  15. if (window.XMLHttpRequest) {
  16. xmlHttp = new XMLHttpRequest();
  17. } else {
  18. xmlHttp = new ActiveXObject('Microsoft.xmlHttp');
  19. }
  20. // 2、发送AJAX请求
  21. xmlHttp.open('GET','http://128.0.0.1/content',true);
  22. xmlHttp.send();
  23. // 3、处理服务器响应
  24. xmlHttp.onreadystatechange = function(){
  25. if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
  26. var t = xmlHttp.responseText;
  27. document.getElementById('divContent').innerHTML = t;
  28. }
  29. }
  30. }
  31. </script>
  32. </html>

review0617-5

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX测试2</title>
</head>
<body>
    <div id="container"></div>
</body>
<script type="text/javascript">
    // 1、创建xmlhttprequest对象
    var xmlHttp;
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else {
        xmlHttp = new ActiveXObject('Microsoft.xmlHttp');
    }
    console.log('first');
    // 2、发送AJAX请求
    xmlHttp.open('GET','http://127.0.0.1:8080/news_list',true);
    xmlHttp.send();
    console.log('second');
    // 3、处理服务器响应
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            var t = xmlHttp.responseText;
            // console.log(typeof t);
            var json = JSON.parse(t);
            // console.log(json);
            var html = '';
            for (var i=0;i<json.length;i++){
                var news = json[i];
                html = html + '<h1>' + news.title + '</h1>';
                html = html + '<h2>' + news.date + '&nbsp' + news.source + '</h2>';
                html = html + '</hr>';
            }
            document.getElementById('container').innerHTML = html;
        }
    }
    console.log('third');
</script>
</html>