如何在JavaScript中将Ajax转换为Fetch API? [英] How to convert Ajax to Fetch API in JavaScript?

查看:177
本文介绍了如何在JavaScript中将Ajax转换为Fetch API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用的是 RiveScript的JavaScript端口使用ajax,当然我不想再使用jQuery了。只有一行ajax,我想将其更改为新的Fetch API。

So I am using the JavaScript port of RiveScript which uses ajax and of course I don't want to use jQuery anymore. There is only one line ajax and I want to change it to the new 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:

and here's what I tried so far using the 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,我现在没有看到任何错误,但我也没有看到任何错误或成功消息。

Using the Fetch API, I'm not seeing any error now though I'm also not seeing any error or success messages.

我在这里遗漏了什么吗?

Am I missing something here?

推荐答案

获取init对象没有' t有一个 dataType 键。

The fetch init object doesn’t have a dataType key.

要表明你想要纯文本,请添加接受:text / plain 请求标头:

To indicate you want plain text back, add an Accept: text/plain header to the request:

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

并且 fetch 调用返回一个使用 Response object ,以及 Response object提供以方法 =https://developer.mozilla.org/en-US/docs/Web/API/Body/text =nofollow noreferrer> text , JSON数据,或 Blob - 表示处理获取响应的基本表单( ...)调用是这样的:

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(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.

这篇关于如何在JavaScript中将Ajax转换为Fetch API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆