在golang中使用ajax将javascript变量发布到mysql

时间:2018-03-23 07:36:36

标签: javascript jquery mysql ajax go

我使用javascript找到屏幕大小,并希望此数据使用ajax发布mysql。但这不起作用。如何在new.go文件中定义屏幕大小变量?如何使用ajax将自动创建的屏幕大小信息发布到mysql?

以下是new.html代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Call Go</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script type="text/javascript">


            (function (window) {


                    // screen
                    var screenSize = '';
                    if (screen.width) {
                        width = (screen.width) ? screen.width : '';
                        height = (screen.height) ? screen.height : '';
                        screenSize += '' + width + " x " + height;
                    }


                window.jscd = {
                    screen: screenSize,
                };
            }(this));
            alert(
                'Screen Size: ' + jscd.screen
            );


                    $("#callGo").on('click', function() {
                    $.ajax({
                        url: "http://localhost:9000/callme",
                        method: "POST",
                        success: function() {
                            $("#response").html(jscd.screen);
                        },
                    });
                });

        </script>
    </head>
    <body>
        <button id="callGo" type="submit">Call Go Code</button>
        <div id="response"></div>
    </body>
</html>

当我点击callGo命名按钮时,必须显示响应名为div success的添加文本。但是我该怎么做?如何连接ajax发送数据到后端代码插入mysql?

这是我的new.go文件

package main

import (
    "database/sql"
    "html/template"
    "log"
    "net/http"

    _ "github.com/go-sql-driver/mysql"
)

// Load the index.html template.
var tmpl = template.Must(template.New("tmpl").ParseFiles("new.html"))

func main() {
    // Serve / with the index.html file.
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if err := tmpl.ExecuteTemplate(w, "new.html", nil); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    })

    // Serve /callme with a text response.
    http.HandleFunc("/callme", func(w http.ResponseWriter, r *http.Request) {

        db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/test_db")
        defer db.Close()
        if err != nil {
            panic(err.Error())
        }
        if r.Method == "POST" {
            insForm, err := db.Prepare("INSERT INTO screen(screen_size) VALUES(?)")
            if err != nil {
                panic(err.Error())
            }
            insForm.Exec(jscd.screen)

        }

        http.Redirect(w, r, "/", 301)
    })

    // Start the server at http://localhost:9000
    log.Fatal(http.ListenAndServe(":9000", nil))
}

0 个答案:

没有答案