如何在HTML按钮onClick中调用Rust函数并传递输入参数?
实现HTML按钮点击触发Rust后端函数(传递prompt参数)
核心逻辑说明
前端浏览器无法直接调用后端Rust函数,必须通过HTTP请求触发后端路由,再由路由调用目标submit函数。以下是具体实现步骤:
步骤1:修改Rust后端代码,添加POST路由
新增一个POST路由,接收前端传来的prompt参数并调用submit函数:
use rocket_dyn_templates::{context, Template}; use serde::Serialize; use rocket::form::Form; #[derive(Serialize)] struct Context { prompt: String, } #[derive(FromForm)] struct PromptInput { prompt: String, } #[macro_use] extern crate rocket; fn submit(prompt: String) { println!("value is {prompt}"); } #[get("/")] fn index() -> Template { let prompt: String = "".to_string(); Template::render("index", context! { field: prompt }) } // 新增POST路由,处理前端提交的请求 #[post("/submit", data = "<input>")] fn handle_submit(input: Form<PromptInput>) -> &'static str { submit(input.prompt.clone()); "Prompt submitted successfully!" } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![index, handle_submit]) .attach(Template::fairing()) }
步骤2:修改前端HTML,实现点击发送请求
提供两种实现方式,任选其一即可:
方式一:JavaScript发送POST请求(支持自定义交互)
为按钮绑定点击事件,通过JS获取输入值并发送请求:
<head> <style type="text/css"> title { display: block; content: "Generator Image"; } body { background: #1a6875; font-family: Arial, Helvetica, sans-serif; } .container-prompt { height: 10em; display: flex; align-items: center; justify-content: center; } .submit-prompt { margin: 0; } </style> </head> <body> <div class="container-submit"> <div class="submit-prompt"> <input type="text" name="prompt" id="prompt"/> <button onClick="sendPrompt()">Submit</button> </div> </div> <script> function sendPrompt() { const promptValue = document.getElementById('prompt').value; fetch('/submit', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `prompt=${encodeURIComponent(promptValue)}` }) .then(response => response.text()) .then(data => { console.log(data); document.getElementById('prompt').value = ''; }) .catch(error => console.error('Error:', error)); } </script> </body>
方式二:HTML表单提交(无需额外JS)
用<form>标签包裹输入框和按钮,通过表单默认提交逻辑触发请求:
<head> <style type="text/css"> title { display: block; content: "Generator Image"; } body { background: #1a6875; font-family: Arial, Helvetica, sans-serif; } .container-prompt { height: 10em; display: flex; align-items: center; justify-content: center; } .submit-prompt { margin: 0; } </style> </head> <body> <div class="container-submit"> <div class="submit-prompt"> <form action="/submit" method="POST"> <input type="text" name="prompt" id="prompt"/> <button type="submit">Submit</button> </form> </div> </div> </body>
注意事项
- 原HTML中输入框的
method="text"属性错误,已修正为type="text"。 - 如果需要用JSON格式传递参数,只需调整后端接收逻辑(使用
Json代替Form)和前端请求的Content-Type为application/json。
内容的提问来源于stack exchange,提问作者koda777
相关产品推荐
相关产品推荐

