Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从javascript代码中调用Golang函数_Javascript_Go - Fatal编程技术网

从javascript代码中调用Golang函数

从javascript代码中调用Golang函数,javascript,go,Javascript,Go,我正在开发一个webapp,它已经有了一个布局css、bootstrapv.3和一个index.html。我已经成功地加载了Golang启动并运行的项目。我嵌入了一个注册按钮,单击该按钮可以从处理http请求的server.Go文件中调用Go函数 $(document).ready(function() { $('#signup').on('click', loginHandler); }); 我有一个server.go文件,如下所示: package main import

我正在开发一个webapp,它已经有了一个布局css、bootstrapv.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) {

}
$.ajax({
  url: "http://www.example.com/signup",
  data: {username: "whatever"} //If the request needs any data 
}).done(function (data) {
  // Do whatever with returned data
});
所以问题是,当点击一个注册Id为的按钮实例时,如何触发server.go文件中的golang loginHandler函数?
如果您对此有任何想法,我们将不胜感激。

您正在寻找的是AJAX(AsynchronousJavascriptAndXml)。它是一种JavaScript技术,允许您发出异步HTTP请求以从服务器获取数据。看起来您正在使用jQuery,并将jQuery与AJAX结合使用,如下所示:

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) {

}
$.ajax({
  url: "http://www.example.com/signup",
  data: {username: "whatever"} //If the request needs any data 
}).done(function (data) {
  // Do whatever with returned data
});
如果需要,可以专门为
GET
POST
使用函数:

$.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
});
甚至可以在没有jQuery的情况下执行AJAX:

var req = new XMLHTTPRequest();
req.addEventListener("load", function (data) {// Do whatever});
req.open("get", "http://example.com", true);
req.send();
如果您需要AJAX的参考资料,请访问以下几个站点:

jQuery

香草JavaScript