首页 > 解决方案 > 使用 NodeJS 完成 AJAX 请求时页面重新加载

问题描述

我正在尝试使用 get 请求来运行 python 脚本并使用 AJAX、Nodejs(使用 express)和 Python-Shell(运行服务器端 python 脚本)返回结果。我希望将此结果返回到我页面上的 div 中。

该代码确实将 python 脚本的结果返回到网页中(它在 div 中闪烁了一秒钟),但随后几乎立即重新加载页面。

我的客户端 JS 函数(通过按钮 onclick 事件触发)

function getResult() {
    xmlhttp = new XMLHttpRequest()
    ResultCoords = encodeURI('oLat=' + document.getElementById('originLat').innerHTML + '&oLng=' + document.getElementById('originLng').innerHTML + '&dLat=' + document.getElementById('destLat').innerHTML + '&dLng=' + document.getElementById('destLng').innerHTML);
    xmlhttp.open("GET", "http://localhost:3000/run?" + ResultCoords, false);
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            string = xmlhttp.responseText;
            document.getElementById('result').innerHTML = string
        }
    }
    xmlhttp.send(ResultCoords)
}

我的服务器端脚本

router.get('/run?*', (req, res) => {
    let options = {
        mode: 'text',
        pythonPath: 'my python path',
        pythonOptions: ['-u'],
        scriptPath: 'my script path',
        args: [req.query.oLat, req.query.oLng, req.query.dLat, req.query.dLng]
    };
    PythonShell.run('pythonScript.py', options, function (err, results) {
        if (err) throw err;
        console.log(results);
        const data = results;
        return res.send(data)
    });
});

我仍然是 express、AJAX 等的初学者,所以如果这不是做这些事情的正确方法等,我愿意接受任何关于改进代码的建议。

谢谢!

标签: javascriptnode.jsajaxexpress

解决方案


推荐阅读