【问题标题】:Ajax XMLHttpRequest instance methods ivocationAjax XMLHttpRequest 实例方法调用
【发布时间】:2016-03-06 15:35:26
【问题描述】:
function getJSON(url, placeholderForCallback){
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.onprogress = function(event){
        console.log(event.loaded, event.total);
    };
    request.addEventListener('load', function(){
        if(request.status < 400){
            placeholderForCallback(request);
        }
    });
    request.send(null);
}

getJSON('http://api.open-notify.org/astros.json', function(placeholder){
    console.log(placeholder.responseText);
});

我有三个问题:

1.将哪个事件传递给函数request.onprogress()

2. 为什么我看不到request.onprogres() 调用?相反,在初始化之前有一个值为null 的属性: printscreen of console

3. 这个事件是每隔一段时间传递给函数还是事件触发?如果发生事件 - 为什么我在任何地方都看不到 request.addEventListener('event', request.onprogres())

【问题讨论】:

  • 通常是好主意) - 将“事件”本身添加到 console.log:request.onprogress = function(event){ console.log(event.loaded, event.total, event) ; };它给了我“XMLHttpRequestProgressEvent”对象

标签: javascript ajax


【解决方案1】:
  1. XMLHttpRequest 对象的 onprogress 属性在服务器报告整体操作的某些进度时被调用。这会触发 XHR 的 Progress 事件,该事件将以下函数存储为该事件的处理程序:

    function(event){
       console.log(event.loaded, event.total);
    } 
    
  2. 进度事件的调用是由服务器进度更新触发的,因此您不会/无法确切知道何时会发生这种情况,但通常每个字节大约每 50 毫秒一次(如此处所述:XmlHttpRequest onprogress interval)。

  3. 是的,每次触发 Progress 事件时,该事件都会传递给您的事件处理程序。这就是为什么您能够获得event.loadedevent.total。每次调用该函数时,都会传递一个带有更新信息的更新事件。

您的代码没有使用 DOM 事件模型“连接”进度事件:

    request.addEventListener('event', functionToHandleEvent);

相反,您的代码使用 onprogress 对象属性来存储处理事件的函数:

   request.onprogress = function(event){
      console.log(event.loaded, event.total);
   };

这种技术确实可以注册您的回调函数,但它是一种较旧的技术。标准(和更新的方式)是:

   request.addEventListener("progress", function(event){
        console.log(event.loaded, event.total);
   });

【讨论】:

  • “XMLHttpRequestProgressEvent”对象是否作为“事件”传递给每个属性:onabort: null onerror: null onload: (event) onloadend: null onloadstart: null onprogress: (event) onreadystatechange: null ontimeout: null
  • 当事件由回调函数处理时,该函数总是将事件对象作为第一个参数传递给函数。所以,是的,您创建的用于处理中止、错误、readystatechange、超时等的函数都将传递给事件对象。只需确保您的回调函数通过为其指定一个参数来接收它,例如 function(evt) {. . . }
【解决方案2】:
  1. 什么事件被传递给函数request.onprogress

根据documentation,它传递了一个具有loadedtotal 属性的对象。

  1. 为什么我看不到 request.onprogres 调用

因为您尝试调用的远程端点 (http://api.open-notify.org/astros.json) 不支持 CORS,因此您的 AJAX 请求永远不会发送。实际发出 AJAX 请求后,将调用进度事件以报告进度。

请注意,除非远程服务器明确支持,否则您不能进行跨域 AJAX 调用。

3.此事件是否每隔一段时间或事件触发时传递给函数?

这是一个在执行AJAX请求的过程中会触发的事件。

【讨论】:

    猜你喜欢
    • 2016-08-30
    • 2010-09-29
    • 1970-01-01
    • 2014-10-12
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多