javascript - 使用 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 等的初学者,所以如果这不是做这些事情的正确方法等,我愿意接受任何关于改进代码的建议。
谢谢!
解决方案
推荐阅读
- asp.net - 使用 ASP.NET Web API 作为 Hangfire 作业存储
- r - 为什么 stCuts 中会出现错误“在 st-cuts.c:415 : Invalid root vertex id for dominator tree, Invalid value”?
- javascript - 数组映射的 JavaScript 内联函数
- linux - 在linux中覆盖环境变量
- django - Django 管理员更改列表隐藏复选框
- pandas - 如何将类别的基础表示设置为 uint8?
- twitter - 如何在 Twitter API 上启用增强的 URL 丰富?
- sql - SQL:如何选择每个唯一标识符的值最低的记录
- asp.net-core - 在启用 Windows 身份验证的情况下,使用 ASP.NET Core 和 Aurelia(使用 http-fetch-client)设置 CORS 的正确方法是什么?
- c# - 在 TFS 构建日志中显示自定义异常消息