在JavaScript中直接执行Go函数是不可能的,因为JavaScript运行在浏览器中,而Go运行在服务器端。你需要通过HTTP请求来触发服务器端的Go函数。以下是几种实现方式:
1. 使用表单提交(最简单的方式)
// Go后端代码
package main
import (
"fmt"
"log"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
log.Printf("Hello world")
fmt.Fprintf(w, "Hello function executed")
}
}
func main() {
http.HandleFunc("/hello", helloHandler)
http.ListenAndServe(":8080", nil)
}
<!-- HTML模板 -->
<form id="myForm" action="/hello" method="POST">
<button type="submit">执行Go函数</button>
</form>
2. 使用Fetch API(推荐方式)
// JavaScript代码
async function SubmitFunction() {
try {
const response = await fetch('/hello', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (response.ok) {
const result = await response.text();
console.log(result);
// 如果需要,可以在这里提交表单
document.getElementById("myForm").submit();
}
} catch (error) {
console.error('Error:', error);
}
}
3. 使用XMLHttpRequest
function SubmitFunction() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/hello", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("Go函数执行成功");
document.getElementById("myForm").submit();
}
};
xhr.send();
}
4. 完整示例:Go后端 + HTML/JS前端
// main.go
package main
import (
"fmt"
"log"
"net/http"
"text/template"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
log.Printf("Hello world")
fmt.Fprintf(w, `{"status": "success", "message": "Hello function executed"}`)
}
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("index.html"))
tmpl.Execute(w, nil)
}
func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/hello", helloHandler)
log.Println("服务器启动在 http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>执行Go函数示例</title>
</head>
<body>
<form id="myForm" action="/submit" method="POST">
<!-- 表单内容 -->
</form>
<button onclick="SubmitFunction()">执行Go函数并提交表单</button>
<script>
async function SubmitFunction() {
// 先执行Go函数
const response = await fetch('/hello', {
method: 'POST'
});
if (response.ok) {
const data = await response.json();
console.log(data.message);
// 然后提交表单
document.getElementById("myForm").submit();
}
}
</script>
</body>
</html>
运行Go服务器后,当用户点击按钮时,会先向/hello端点发送POST请求执行Go函数,然后提交表单。