我正在嘗試構建一個 Excel 加載項,它使用 AJAX 根據內容從另一臺服務器獲取資料。我創建了以下簡單原型,它進行簡單的 get 呼叫并將結果寫入單元格。AJAX 呼叫尚未使用 Excel 的內容,但將來會用到。
Excel.run(function (context) {
let sourceRange = context.workbook.getSelectedRange().load("values, rowCount, columnCount");
return context.sync()
.then(function() {
return $.ajax("https://localhost:44381/");
})
.then(function (data, status) {
let values = [[ "Result:" data status ]];
sourceRange.values = values;
})
.then(context.sync);
}).catch(errorHandler);
一切似乎都正常,除了狀態,它總是未定義的。這很奇怪,因為資料是正確的。我已經在 context.sync() 承諾鏈之外嘗試過它,它作業得非常好。狀態應該是“成功”,并且它確實適用then(function(data, status)...于像這樣的承諾鏈。我已經使用以下代碼進行了嘗試:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax("https://localhost:44381/")
.then(function(data, status){
alert(data status);
})
.then(function() {
return $.ajax("https://localhost:44381/");
})
.then(function(data, status){
alert(data status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
為什么它沒有收到狀態?我該如何解決?
uj5u.com熱心網友回復:
標準承諾只有一個“回傳值”。他們的.then()回呼永遠不會有第二個引數。context.sync()回傳一個標準的承諾,這就是為什么status沒有填寫你的代碼。
另一方面,jQuery 的延遲實作做的事情不同,jQuery 自己的.then()回呼可以接收多個引數。$.ajax()回傳延遲的 jQuery。
Deferreds 在很大程度上與標準 Promise 兼容,這就是為什么您可以首先將它們組合起來。但是與標準的偏差,如輔助回呼引數,會丟失。
如果你需要將status引數捕獲到一個常規的 Promise 中,你必須使用 jQuery 自己的.then()作為幫助器:
return context.sync()
.then(() => {
return $.ajax("https://localhost:44381/").then((data, status) => {
return {data, status};
});
}).then(response => {
// now you have response.data and response.status
});
在這里,jQuery.then()通過將各個引數包裝在 object 中來生成單個值{data: ..., status: ...},并將其傳遞給封閉的原生 Promise。
$.ajax()如果您更頻繁地需要它,您可以制作一個包裝器。
function jqAjax() {
return new Promise((resolve, reject) =>
$.ajax.apply($, arguments).then(
(data, status, jqXHR) => resolve({data, status, jqXHR}),
(jqXHR, status, error) => reject({error, status, jqXHR})
)
);
}
這將為您提供標準的承諾行為,作為交換,您將失去對 jQuery 自己的延遲 API 的訪問權限,即像.done()or 之類的東西.always()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406641.html
標籤:
上一篇:有效負載未傳遞給處理程式
