• 关于Ajax使用 Callback 函数


    1、onreadystatechange 事件

    当请求被发送到服务器时,我们需要执行一些基于响应的任务。

    每当 readyState 改变时,就会触发 onreadystatechange 事件。

    readyState 属性存有 XMLHttpRequest 的状态信息。

    属性描述
    onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
    readyState

    存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

    • 0: 请求未初始化
    • 1: 服务器连接已建立
    • 2: 请求已接收
    • 3: 请求处理中
    • 4: 请求已完成,且响应已就绪
    status

    200: "OK"

    404: 未找到页面

    在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。

    当 readyState 等于 4 且状态为 200 时,表示响应已就绪:

    <html>
    <head>
    <script type="text/javascript">
    function loadXMLDoc()
    {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","/ajax/test1.txt",true);
    xmlhttp.send();
    }
    </script>
    </head>
    <body>
    
    <div id="myDiv"><h2>Let AJAX change this text</h2></div>
    <button type="button" onclick="loadXMLDoc()">通过 AJAX 改变内容</button>
    
    </body>
    </html>

    注释:onreadystatechange 事件被触发 5 次(0 - 4),对应着 readyState 的每个变化。

    2、使用 Callback 函数

    callback 函数是一种以参数形式传递给另一个函数的函数。

    如果您的网站上存在多个 AJAX 任务,那么您应该为创建 XMLHttpRequest 对象编写一个标准的函数,并为每个 AJAX 任务调用该函数。

    该函数调用应该包含 URL 以及发生 onreadystatechange 事件时执行的任务(每次调用可能不尽相同):

    <html>
    <head>
    <script type="text/javascript">
    var xmlhttp;
    function loadXMLDoc(url,cfunc)
    {
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=cfunc;
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
    }
    function myFunction()
    {
    loadXMLDoc("/ajax/test1.txt",function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
      });
    }
    </script>
    </head>
    <body>
    
    <div id="myDiv"><h2>Let AJAX change this text</h2></div>
    <button type="button" onclick="myFunction()">通过 AJAX 改变内容</button>
    
    </body>
    </html>
  • 相关阅读:
    Service Fabric 用 Powershell 部署应用到本地
    Redis 高可用之哨兵模式(二)
    Redis 高可用之哨兵模式
    微服务之Service Fabric 系列 (一):概览、环境安装
    Nginx 负载均衡
    Redis 总结
    微服务示例-Spring Cloud
    ASP.NET Core Linux 发布
    Windows RabbitMQ 安装
    Nancy 框架学习
  • 原文地址:https://www.cnblogs.com/iammackong/p/3396145.html
Copyright © 2020-2023  润新知