2017-10-18 7 views
2

私はJavaScript port of RiveScriptを使用しています。これはajaxを使用していますが、もちろんjQueryを使用したくありません。 1行のajaxしかなく、新しいFetch APIに変更したいと思います。JavaScriptでFetch APIにAjaxを変換するには?

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

ので、ここで元のコードです:

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

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

、ここでは私が取得APIを使用して、これまでに試したものだが、 Fetch APIを使用してもエラーは表示されません今でもエラーメッセージや成功メッセージは表示されません。

ここに何か不足していますか?

+0

'.then()'から関数を返す目的は何ですか? – guest271314

答えて

2

fetch init objectにはdataTypeキーがありません。

、あなたが戻ってプレーンテキストを望ん示す要求にAccept: text/plainヘッダを追加するには:

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

そしてfetch呼び出しがResponse objectを解決する約束を返し、Responseオブジェクトがtextで解決methodsを提供しています、JSON data、またはBlob - あなたのfetch(…)コールからの応答を処理するための基本的な形態を意味する。このようなものです:

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

したがって、質問の既存のコードを取り、そのフォームに適合させる必要があります。

+0

ありがとうございます。私は最終的にテキストを取得し、今度は必要に応じて適切に変換します。 – FewFlyBy

関連する問題