XMLHttpRequest:loadend 事件
基線 廣泛可用
此功能已非常成熟,並在許多裝置和瀏覽器版本中執行良好。它自 2015 年 7 月.
報告反饋
注意:此功能在 Web Workers 中可用,但 Service Workers 除外。
語法
loadend 事件在請求完成時觸發,無論成功(在 load 之後)還是失敗(在 abort 或 error 之後)。
在諸如
addEventListener() 之類的 методах 中使用事件名稱,或設定事件處理程式屬性。addEventListener("loadend", (event) => {});
onloadend = (event) => {};
事件型別
js
事件屬性
一個 ProgressEvent。繼承自 Event。
示例
一個 64 位無符號整數,表示基礎程序正在執行的總工作量。使用 HTTP 下載資源時,這就是 Content-Length(訊息主體的大小),不包括標頭和其他開銷。
HTML
即時示例
<div class="controls">
<input
class="xhr success"
type="button"
name="xhr"
value="Click to start XHR (success)" />
<input
class="xhr error"
type="button"
name="xhr"
value="Click to start XHR (error)" />
<input
class="xhr abort"
type="button"
name="xhr"
value="Click to start XHR (abort)" />
</div>
<textarea readonly class="event-log"></textarea>
JavaScript
在諸如
addEventListener() 之類的 методах 中使用事件名稱,或設定事件處理程式屬性。const xhrButtonSuccess = document.querySelector(".xhr.success");
const xhrButtonError = document.querySelector(".xhr.error");
const xhrButtonAbort = document.querySelector(".xhr.abort");
const log = document.querySelector(".event-log");
function handleEvent(e) {
log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`;
}
function addListeners(xhr) {
xhr.addEventListener("loadstart", handleEvent);
xhr.addEventListener("load", handleEvent);
xhr.addEventListener("loadend", handleEvent);
xhr.addEventListener("progress", handleEvent);
xhr.addEventListener("error", handleEvent);
xhr.addEventListener("abort", handleEvent);
}
function runXHR(url) {
log.textContent = "";
const xhr = new XMLHttpRequest();
addListeners(xhr);
xhr.open("GET", url);
xhr.send();
return xhr;
}
xhrButtonSuccess.addEventListener("click", () => {
runXHR(
"https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json",
);
});
xhrButtonError.addEventListener("click", () => {
runXHR("http://i-dont-exist");
});
xhrButtonAbort.addEventListener("click", () => {
runXHR(
"https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json",
).abort();
});
html
規範
| 結果 |
|---|
| 規範 # XMLHttpRequest 標準 |
| 規範 # event-xhr-loadend |
瀏覽器相容性
handler-xhr-onloadend