简体   繁体   English

无法从 Javascript 中的 API 捕获响应

[英]Unable to capture response from an API in Javascript

I am using below code to capture response but unable to get, please let me know what I am missing here.我正在使用下面的代码来捕获响应但无法获得,请让我知道我在这里遗漏了什么。

 function testcall() { var request = new XMLHttpRequest(); request.open('GET', 'http://demo8951713.mockable.io/fusionchart', true); request.send(); var response = this.responseText; alert(response); } testcall()

You have two problems.你有两个问题。

First, this (in the context you are using it) does not refer to your XHR object.首先, this (在您使用它的上下文中)不是指您的 XHR 对象。

Second, you are trying to read the response as soon as the request has been sent.其次,您正在尝试在发送请求后立即读取响应。 You have to wait until the browser has received the response!您必须等到浏览器收到响应!

request.addEventListener("load", function () {
    var response = this.responseText;
    alert(response);
});

That change (moving the code to an event handler) also puts this in a context where it refers to the correct object.这一变化(移动所述代码到事件处理程序)也使this它指的是正确的对象中的上下文。


Once you have fixed this, you are likely to want to try to return the value.一旦你解决了这个问题,你可能想要尝试返回值。 Before you do, read this question .之前,请阅读此问题

you are missing the callback function你缺少回调函数

request.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        callback(xhr.response);
    }
}

for more details, refer https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response#Example有关更多详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response#Example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM