[英]how can I create a fake promise that answers with a done function?
我有這段代碼,如果 vID=0 則不起作用,因為 ajax.done 不是函數:
if (vID > 0) {
var ajax = CallPHP('GET', 'grid_main.php', "idquery=7&trkbid=" + vID);
} else {
// Here I need a fake ajax so that the following code will work
var ajax=new Promise();
};
ajax.done(function(data, textStatus, jqXHR) {
// do something
}
我該如何解決? 謝謝
更合乎邏輯的是創建一個函數並調用它。
function nextStep(data, textStatus, jqXHR) {
// do something
}
if (vID > 0) {
var ajax = CallPHP('GET', 'grid_main.php', "idquery=7&trkbid=" + vID).done(nextStep);
} else {
nextStep({});
};
你不能使用promise,因為jQuery 的Ajax 對象不是promise。 它必須看起來像
var ajax = { done: function(method) { method({}); } }; ajax.done(function(data, textStatus, jqXHR) { console.log(data); });
你可以使用 jQuery 的 deferred
var ajax = $.Deferred().resolve({}); ajax.done(function(data, textStatus, jqXHR) { console.log(data); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.