2015-03-30 85 views
2

我正在研究一個已經具有佈局CSS,引導程序v.3和index.html的web應用程序。我已成功將Golang項目加載並運行。我已經嵌入了一個註冊按鈕,點擊後應該從處理http請求的server.go文件中調用Go功能。從javascript代碼中調用Golang函數

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

} 

所以,問題是在點擊一個按鈕實例與註冊編號,我怎麼有觸發golang server.go文件中的loginHandler函數? 任何想法在此將不勝感激。

回答

4

你所尋找被稱爲AJAX(一個同步Ĵ 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的執行:如果您需要AJAX參考

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

,這裏有幾個網站:

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

相關問題