javascript - 我如何知道 XHR 已使用 readState 发送到服务器?

标签 javascript ajax xmlhttprequest

这个问题与我之前的问题相关: Is READYSTATE_LOADED across browsers?

所以我知道readyState在浏览器中并不可靠。目前我正在尝试在任何浏览器中进行概念验证。

我在我的插件中并且有这样的代码:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){            

  if (xhr.readyState == 4){
      self._onComplete(id, xhr);                    
  }
  else if (xhr.readyState == 2 ){
    self._onSent( id, xhr );
  }

};

如果我记录回调,则在服务器端脚本响应之后,“发送”会在“完成”之前立即触发。我是否误解了readyState 2是什么?我尝试了 1 来踢球,但在服务器响应之前也没有触发。

我查看了 xhr 对象的上传对象,它至少有一个“进度”事件,但我仍然没有看到任何有关正在完成的进度的信息。事实上,如果最后的进度为 97%,当文件完成发送到服务器时,它不会以 100% 的速度触发。因此,当服务器处理上传时,在readyState变为4之前,进度卡在97%。

这会让用户认为上传已停止,即使实际上上传速度一直在上升。

最佳答案

没有状态可以检查请求何时被发送。

readyState 2 表示服务器已响应并且所有 header 均已传入。这会在请求的主体部分传入之前触发。

最好的办法是在发出 send() 命令时触发自己的事件。

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){            

  if (xhr.readyState == 4){
      self._onComplete(id, xhr);                    
  }
  else if (xhr.readyState == 2 ){
    // Headers received
  }

};

xhr.send(data)
self._onSend( id, xhr );

4.6 States

UNSENT (numeric value 0) The object has been constructed.

OPENED (numeric value 1) The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2) All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

LOADING (numeric value 3) The response entity body is being received.

DONE (numeric value 4) The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

http://www.w3.org/TR/XMLHttpRequest/#states

编辑

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){            

  if (xhr.readyState == 4){
      self._onComplete(id, xhr);                    
  }
  else if (xhr.readyState == 2 ){
    // Headers received
  }
  else if (xhr.readyState == 1 ){
    // xhr.open() called
    // You can set headers here amoung other things
    xhr.send(data)
    self._onSend( id, xhr );
  }

};

xhr.open(method, url, async, user, password)

http://www.w3.org/TR/XMLHttpRequest/#the-open-method

关于javascript - 我如何知道 XHR 已使用 readState 发送到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11678898/

相关文章:

javascript - 无法解析 Ajax 调用错误部分中的 json 对象值

javascript - 是否有函数可以查找当前使用 XMLHtttpRequest 从文件加载的字节数?

javascript - 阻止 Chrome 中不包含特定模式的请求 URL

javascript - 使用 TypeScript 打字的样式化系统 Prop

javascript - JS for 循环问题

javascript - 使用 :contains to found a text jquery

javascript - 我想从数据库加载事件日历,返回值失效并且日期不显示

javascript - 最好将每次搜索的所有数据发送到客户端或查询服务器?

javascript - 从 xmlhttp 数组 javascript 变量中删除 [ 和 ]

javascript - 为什么 javascript 没有生成整数的随机函数?