2017-10-18 31 views
2

所以我使用的是使用ajax的JavaScript port of RiveScript,當然我不想再使用jQuery。只有一行ajax,我想將其更改爲新的Fetch API。如何將Ajax轉換爲JavaScript中的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) 
}); 

這裏是我的嘗試迄今使用的提取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,我沒有看到任何錯誤現在雖然我也沒有看到任何錯誤或成功消息。

我在這裏錯過了什麼嗎?

+0

從'.then()'返回函數的目的是什麼? – guest271314

回答

2

fetch init object沒有dataType鍵。

要註明你要純文本後面,一個Accept: text/plain頭添加到請求:

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

而且fetch調用返回一個帶有Response object解決了一個承諾,那Response對象提供methodstext解決,JSON data,或Blob - 這意味着基本形式用於處理從fetch(…)調用的響應是這樣的:

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

因此,您需要將問題中的現有代碼填入該表單中。

+0

謝謝先生。我終於得到了文本,現在可以根據需要正確轉換它。 – FewFlyBy

相關問題