Javascript 新手陷入 XMLHttpRequest 返回数据困境

标签 javascript

自从我上次使用 JavaScript 以来可能已经有十多年了,所以现在就开始吧。我正在尝试显示来自后端数据库和/或 ESP32 微 Controller 的图表。很容易从示例生成静态 HTML/CSS/JavaScript 图表,但我需要图表每秒更新实时数据。我可以让 JavaScript 通过 XMLHttpRequest 调用数据库并返回数据,但我不知道如何将其返回到更新图表的变量中。

我在 https://www.amcharts.com/ 上或多或少找到了项目所需的图表。 .

// using chart.setTimeout method as the timeout will be disposed together with a chart
 chart.setTimeout(randomValue, 1000);

function randomValue() {
    //hand.showValue(Math.random() * 1000, 1000, am4core.ease.cubicOut); // <----- sample code supplied
    //hand.showValue(550); // <---- my test code which works

    // after some googling I found this...
    function reqListener () {
        console.log(this.responseText);
    //alert(oReq.responseText); // <---- when un-commented I can see my data that the database is returning every second, just an integer value and nothing else.
    }

    var oReq = new XMLHttpRequest();
    oReq.addEventListener("load", reqListener);
    oReq.open("GET", 'http://myurl.com');
    oReq.send();

    hand.showValue(oReq.responseText); <<<<<< what do I put in the () to show the same data that the alert above displays correctly?

    chart.setTimeout(randomValue, 1000); // < original supplied sample code
}

什么也没发生...我也不知道:)

最佳答案

XMLHttpRequest 要求您添加事件监听器并等待 load 事件。一旦请求完成,这将告诉您,然后您可以对响应执行某些操作。

查看此网站以获取更详细的说明: https://javascript.info/xmlhttprequest

关于Javascript 新手陷入 XMLHttpRequest 返回数据困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57536781/

相关文章:

javascript - 为什么 RequireJS 在使用优先级时不起作用?

javascript - Magento - opcheckout.js - 在结帐期间手动调用 setAddress()

javascript - 从屏幕外动画一个 div,没有绝对位置?

javascript - 在哪里可以使用 React 中的 hooks 进行 API 调用?

javascript - JS : How to find double question mark in string

javascript - 如何导出没有大括号的扩展类? ( Node JS)

javascript - CSS:导航栏在稳定之前跳来跳去

javascript - xml2json jQuery 插件不起作用

Javascript (0 && 1)

javascript - Easyautocomplete 链接和图像