zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    对象属性键值[key]属性问题
    理解 JavaScript 中的 for…of 循环
    vue初学篇----过滤器(filters)
    CSS变量
    SCSS !default默认变量
    vue 集成 NEditor 富文本
    如何在Github上面精准搜索开源项目?
    OSS介绍
    键盘各键对应的编码值(key code)
    网易云音乐歌单生成外链播放器
  • 原文地址:https://www.cnblogs.com/patriot/p/5630240.html
Copyright © 2011-2022 走看看