首页 > 解决方案 > 将响应传递给 addEventListener 中的函数

问题描述

我正在使用一个 API,其中响应来自 addEventListener 函数,我想在收到响应后将其传递给函数。我正在努力实现以下目标:

getToken() {
    var data = JSON.stringify({
        "app_key": "my_app_key",
        "app_secret": "my_app_secret"
    });

    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;

    xhr.addEventListener("readystatechange", async function () {
      if (this.readyState === this.DONE) {
        console.log(this.responseText);
        await val = this.responseText;
        this.recieveApiResponse(val);
      }
    });

    xhr.open("POST", "https://tokenized.sandbox........../grant");
    xhr.setRequestHeader("username", "my_username");
    xhr.setRequestHeader("password", "my_password");

    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.send(data);
}

recieveApiResponse(resp) {
    console.log(resp)
}

标签: javascriptreactjsreact-nativeasync-awaitdom-events

解决方案


推荐阅读