简体   繁体   English

如何在JavaScript中将Ajax转换为Fetch API?

[英]How to convert Ajax to Fetch API in JavaScript?

So I am using the JavaScript port of RiveScript which uses ajax and of course I don't want to use jQuery anymore. 所以我使用的是使用ajax 的RiveScriptJavaScript端口,当然我不想再使用jQuery了。 There is only one line ajax and I want to change it to the new Fetch API. 只有一行ajax,我想将其更改为新的Fetch API。

**FYI: You can see the ajax code in line 1795 of the CDN.**

So here's the original code: 所以这是原始代码:

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)
});

and here's what I tried so far using the Fetch API: 这是我到目前为止使用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);
            }
        };
    })

The app code: 应用代码:

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);
}

Using the Fetch API, I'm not seeing any error now though I'm also not seeing any error or success messages. 使用Fetch API,我现在没有看到任何错误,虽然我也没有看到任何错误或成功消息。

Am I missing something here? 我在这里错过了什么吗?

The fetch init object doesn't have a dataType key. fetch init对象没有dataType键。

To indicate you want plain text back, add an Accept: text/plain header to the request: 要表明您希望返回纯文本,请在请求中添加Accept: text/plain标头:

fetch(file, {
    headers: {
      "Accept": "text/plain"
    },
  })

And the fetch call returns a promise that resolves with a Response object , and that Response object provides methods that resolve with text , JSON data , or a Blob — which means the basic form for handling the response from your fetch(…) call is like this: 并且fetch调用返回一个使用Response对象解析的promise,而Response对象提供了使用textJSON数据Blob解析的方法 - 这意味着处理来自fetch(…)调用的响应的基本形式就像这个:

fetch(file, {
  headers: {
    "Accept": "text/plain"
  },
})
.then(response => response.text())
.then(text => {
  // Do something with the text
})

So you need to take the existing code in the question and fit it into that form. 因此,您需要获取问题中的现有代码并使其适合该表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM