所以我正在使用使用 ajax的 RiveScript 的 JavaScript 端口,当然我不想再使用 jQuery 了。只有一行 ajax,我想将其更改为新的 Fetch API。
**FYI: You can see the ajax code in line 1795 of the CDN.**
所以这里是原始代码:
return $.ajax({
url: file,
dataType: "text",
success: (function(_this) {
return function(data, textStatus, xhr) {
_this.say("Loading file " + file + " complete.");
_this.parse(file, data, onError);
delete _this._pending[loadCount][file];
if (Object.keys(_this._pending[loadCount]).length === 0) {
if (typeof onSuccess === "function") {
return onSuccess.call(void 0, loadCount);
}
}
};
})(this),
error: (function(_this) {
return function(xhr, textStatus, errorThrown) {
_this.say("Ajax error! " + textStatus + "; " + errorThrown);
if (typeof onError === "function") {
return onError.call(void 0, textStatus, loadCount);
}
};
})(this)
});
到目前为止,这是我使用 Fetch API 尝试过的:
return fetch(file, {
dataType: "text"
})
.then(function(_this) {
return function(data, textStatus, xhr) {
_this.say("Loading file " + file + " complete.");
_this.parse(file, data, onError);
delete _this._pending[loadCount][file];
if (Object.keys(_this._pending[loadCount]).length === 0) {
if (typeof onSuccess === "function") {
return onSuccess.call(void 0, loadCount);
}
}
};
})
.catch(function(_this) {
return function(xhr, textStatus, errorThrown) {
_this.say("Ajax error! " + textStatus + "; " + errorThrown);
if (typeof onError === "function") {
return onError.call(void 0, textStatus, loadCount);
}
};
})
应用代码:
var bot = new RiveScript();
bot.loadFile("./brain.rive", loading_done, loading_error);
function loading_done (batch_num) {
console.log("Batch #" + batch_num + " has finished loading!");
bot.sortReplies();
var reply = bot.reply("local-user", "Hello, bot!");
console.log("The bot says: " + reply);
}
function loading_error (error) {
console.log("Error when loading files: " + error);
}
使用 Fetch API,我现在没有看到任何错误,尽管我也没有看到任何错误或成功消息。
我在这里错过了什么吗?