簡體   English   中英

無法從 Javascript 中的 API 捕獲響應

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

我正在使用下面的代碼來捕獲響應但無法獲得,請讓我知道我在這里遺漏了什么。

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

你有兩個問題。

首先, this (在您使用它的上下文中)不是指您的 XHR 對象。

其次,您正在嘗試在發送請求后立即讀取響應。 您必須等到瀏覽器收到響應!

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

這一變化(移動所述代碼到事件處理程序)也使this它指的是正確的對象中的上下文。


一旦你解決了這個問題,你可能想要嘗試返回值。 之前,請閱讀此問題

你缺少回調函數

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

有關更多詳細信息,請參閱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