2017-04-10 65 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) }