我在 Eclipse 中编写了一个处理程序,它生成图像并将其保存到我的计算机上的特定位置。
有没有办法从 javascript 文件运行该程序,以便当用户单击网页上的按钮时,调用处理程序中的相应方法,生成图像,最后将图像显示在网页。
我在这方面没有太多经验,但我想我可以让处理方法在保存图像后发出 POST 请求,以便将其发送到相关服务器?
我在这里遇到的主要问题是如何从网页实际调用该方法。使用Processing.js或将我的java代码转换为javascript并不是真正的选择,因为我需要将ANTLR导入到我的处理程序中,据我所知,该程序只能与Java一起使用。
需要明确的是,我的程序是一个 .java
文件,它通过导入 processing.core
生成处理草图形式的图像。
我愿意学习新技术等。
非常感谢任何帮助。
最佳答案
您需要从 JavaScript 中调用 HTTP 请求,该请求将触发后端的函数。这可以通过 Fetch API 来实现这是一个获取和发送资源的接口(interface)。
由于您无法在 Web 上运行 Java,因此您需要依赖 JavaScript 客户端和 Java 服务器之间某种形式的通信。您可以来回发送数据以更新两端。
下面我创建了一些示例来说明您的最终结果。您有按钮、与服务器通信的函数以及单击按钮时触发的事件监听器,将按钮连接到函数。
<!-- Create a button in html -->
<button class="process">Process me</button>
// Write a function that sends a HTTP request to your server.
// Can be either POST or GET. Change the 'yoururl' part to your own endpoint.
// The rest of the function will check if the request has been successful and
// returns a string with the received data from the server, if there is any.
function process() {
return fetch('yoururl/process', {
method: 'POST',
}).then(response => {
if (response.status === 200) {
return response.text();
}
}).catch(error => {
console.log(error);
});
}
// Select the button from the HTML.
const button = document.querySelector('.process');
// Fire a function when the button is clicked.
button.addEventListener('click', function(event) {
process().then(text => {
console.log(text); // Show the text that has been received from the server.
});
});
但是您的问题没有明确的答案,因为它非常广泛。我希望至少这能让您朝着正确的方向前进,了解它如何运作。
关于javascript - 从网页调用java方法来生成处理草图并将该草图显示在网页上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59983195/