JavaScript GET responseText

时间:2017-04-10 12:37:35

标签: javascript http get responsetext

我还在学习JavaScript的基础知识,并且我试图制作一个简单的GET Http请求来从API返回信息,但是responseText不会返回。这是代码:



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




1 个答案:

答案 0 :(得分:0)

这是因为你稍后得到回应。 所以你需要处理它异步。要做到这一点,你需要处理回调函数中的响应,这将在你得到响应的那一刻被触发。

我建议你至少使用JQuery - 它在开始时有所帮助。 https://api.jquery.com/jquery.get/

如果您仍然使用xhr(在xhr.send之前)进行操作,我认为它可以使用:

xhr.onreadystatechange = function () { console.log(this.responseText) }
相关问题