繁体   English   中英

从javascript代码中调用Golang函数

[英]calling Golang functions from within javascript code

我正在使用已经具有布局CSS,bootstrap v.3以及index.html的webapp。 我已经使用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同步Ĵavascript X毫升)。 它是一种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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM