gpt4 book ai didi

javascript - 从 JavaScript 代码中调用 Golang 函数

转载 作者:IT王子 更新时间:2023-10-29 01:39:38 45 4
gpt4 key购买 nike

我正在开发一个已经具有布局 css、bootstrap v.3 以及 index.html 的网络应用程序。我已经成功加载了 Golang 项目并运行起来。我嵌入了一个注册按钮,单击该按钮应该会从处理 http 请求的 server.go 文件中调用 Go 函数。

    $(document).ready(function() {
$('#signup').on('click', loginHandler);
});

我有一个这样写的 server.go 文件:

package main

import (
"net/http"

"github.com/bmizerany/pat"
)

func init() {
m := pat.New()

m.Get("/signup", http.HandlerFunc(loginHandler))
m.Get("/", http.HandlerFunc(rootHandler))
http.Handle("/", m)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
}

func loginHandler(w http.ResponseWriter, r *http.Request) {

}

所以问题是在单击具有注册 ID 的按钮实例时,我必须如何触发 server.go 文件中的 golang loginHandler 函数?对此有任何想法将不胜感激。

最佳答案

您正在寻找的是 AJAX(A同步 Javascript Aand Xml)。它是一种 JavaScript 技术,允许您发出异步 HTTP 请求以从服务器获取数据。看起来您正在使用 jQuery,并且将 jQuery 与 AJAX 一起使用,看起来像这样:

$.ajax({
url: "http://www.example.com/signup",
data: {username: "whatever"} //If the request needs any data
}).done(function (data) {
// Do whatever with returned data
});

如果需要,您可以使用专门用于 GETPOST 的函数:

$.get("url: "http://www.example.com/signup", function (data) {
// Do whatever with the returned data
});

$.post("url: "http://www.example.com/signup", {username: "whatever"}, function (data) {
// Do whatever with the returned data
});

AJAX 甚至可以在没有 jQuery 的情况下执行:

var req = new XMLHTTPRequest();
req.addEventListener("load", function (data) {// Do whatever});
req.open("get", "http://example.com", true);
req.send();

如果您需要 AJAX 引用,这里有几个站点:

jQuery

https://api.jquery.com/jQuery.ajax/

https://api.jquery.com/category/ajax/shorthand-methods/

https://api.jquery.com/category/ajax/

原生 JavaScript

https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

关于javascript - 从 JavaScript 代码中调用 Golang 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29353509/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com