2016-03-06 105 views
0
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); 
}); 

我有三个问题:阿贾克斯XMLHttpRequest实例方法ivocation

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

2.为什么我看不到request.onprogres()的调用?取而代之的是与价值null属性初始化之前: printscreen of console

是本次活动传递给函数的时间或事件火灾每一个时期?万一发生火灾 - 为什么我不能在任何地方看到request.addEventListener('event', request.onprogres())

+0

如平时好主意来算账) - 加入 '事件' 本身的执行console.log: request.onprogress =函数(事件){ 的console.log( event.loaded,event.total,event); }; 它给了我 'XMLHttpRequestProgressEvent' 对象 – Dancyg

回答

0
  1. 当服务器报告整体操作的某些进度时,会调用XMLHttpRequest对象的onprogress属性。这会触发XHR的进展情况,其存储作为该事件的处理程序有以下功能:

    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); 
    }); 
+0

是 'XMLHttpRequestProgressEvent' 对象传递给每个属性: 'onabort:空 的onerror:空 的onload:(事件) onloadend:空 onloadstart:空 onprogress:(事件) onreadystatechange:null ontimeout:null'作为'事件'? – Dancyg

+0

当通过回调函数处理事件时,该函数总是将事件对象作为函数的第一个参数传递。所以,是的,您创建的用于处理中止,错误,readystatechange,超时等的函数将全部通过事件对象。只要确保你的回调函数通过指定一个参数来接收它,就像函数(evt){。 。 。 } –

0
  1. what event is passed to the function request.onprogress

按照documentation它传递的对象与在其他loadedtotal性能。

  1. why cannot I see request.onprogres invocation

因为你试图调用远程端点(http://api.open-notify.org/astros.json)不支持CORS和为你的AJAX请求永远不会发送的结果。进度事件将在实际进行AJAX请求后被调用以报告进度。

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

3.this event is passed to the function every period of time or event fire?

这是在执行AJAX请求期间触发的事件。