2017-04-10 63 views
1

我仍然在學習JavaScript的基礎知識,我試圖做一個簡單的GET HTTP請求從API返回的信息,但這個responseText將不會返回。下面的代碼:JavaScript的GET responseText的

var xhr = new XMLHttpRequest(); 
 
xhr.open('GET', "https://api.apithis.net/dictionary.php?define=hi", true); 
 
xhr.send(); 
 
console.log(xhr.responseText)

回答

0

這是因爲你的反應有點晚。 所以你需要處理異步。爲了做到這一點,你需要處理回調函數中的響應,當你得到響應的時候會被觸發。

我建議您至少使用JQuery - 它有助於開始。 https://api.jquery.com/jquery.get/

如果u使用XHR(xhr.send之前)仍然whant它,我認爲它可以使用:

xhr.onreadystatechange = function() { console.log(this.responseText) }