简体   繁体   English

异步 javascript 发布请求的问题

[英]Issue with asynchronous javascript post request

I am trying to simply set a ejs variable to data retrieved through an ajax post request every second.我试图简单地将 ejs 变量设置为每秒通过 ajax post 请求检索的数据。 (refreshing a log) I have tried callback functions, and I feel like I am really close but can't seem to crack it. (刷新日志)我尝试了回调函数,我觉得我真的很接近但似乎无法破解它。

Below is the javascript:下面是javascript:

    function getResults(callback){     
        $.ajax({
            url: '/resultsRefresh',
            type: 'POST',
            async: true,
            cache: false,
            success: callback 
        })
    };

    function setResults(result) {
            console.log("result: " + result);
            document.getElementById("results") = result;
    };
    
    window.setInterval(getResults(setResults), 1000);

And this is the function in question being called on the node server:这是在节点服务器上调用的相关函数:

function readResults(req, res) {
    return fs.readFileSync("./temp/results.txt", 'utf8');
}

which is coming through正在通过

webRouter.post("/resultsRefresh", readResults);

Any help/suggestions would be greatly appreciated.任何帮助/建议将不胜感激。

When responding to requests in the server, you are generally not supposed to return a value, rather you need to call a response function.在响应服务器中的请求时,通常不应该返回值,而是需要调用响应函数。 When using express, res.sendFile does the trick:使用 express 时, res.sendFile可以解决问题:

function readResults(req, res) {
    res.sendFile('./temp/results.txt');
}

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

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