转到嵌入式ajax不显示结果

时间:2018-06-07 11:49:20

标签: html ajax go

我正在努力解决应该是一个明显的问题,但几天之后我仍然陷入困境。我有跟随Go代码......

package main

import (
    "fmt"
    "net/http"
    "html/template"

    "database/sql"
    _"github.com/mattn/go-sqlite3"

    "encoding/json"
)

type Page struct {
    Name string
    DBStatus bool
}

type SearchResult struct {
    Title string
    Author string
    Year string
    ID string
}

func main() {
    db, _ := sql.Open("sqlite3", "dev.db")
    tmpl := template.Must(template.ParseFiles("templates/index.html"))

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("Main Page has been called...")
        p := Page{Name: "Gopher"}
        //Accepts value  passed in with "localhost:8080/?name="
        if name := r.FormValue("name"); name != "" {
            p.Name = name
        }
        p.DBStatus = db.Ping() == nil
        if err := tmpl.ExecuteTemplate(w, "index.html", p); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
        //db.Close()
    })

    http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("Search function has been called...")
        results := []SearchResult {
            SearchResult{"Moby Dick", "Herman Melville", "1851", "222222"},
            SearchResult{"The Adventures of Huckleberry Finn", "Mark Twain", "1884", "444444"},
            SearchResult{"The Catcher in the Rye", "J.D. Salinger", "1951", "666666"},
        }
        fmt.Println("results =", results)

        encoder := json.NewEncoder(w)
        if err := encoder.Encode(results); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    })

    fmt.Println(http.ListenAndServe(":8080", nil))
}

我也有这个嵌入式Javascript的HTML试图从Go ...

获取信息
<html lang="en-US">
    <head>
        <title>Go Web Development</title>
        <meta charset="utf-8" />
    </head>

    <body>
        <form id="search-form" onsubmit="return false">
            <input name="search" />
            <input type="submit" value="Search" onclick="submitSearch()" />
        </form>

        <table width="100%">
            <thead>
                <tr style="text-align: left">
                    <th width="40%">Title</th>
                    <th width="30%">Author</th>
                    <th width="10%">Year</th>
                    <th width="20%">ID</th>
                </tr>
            </thead>
            <tbody id="search-results">

            </tbody>
        </table>

        <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script type="text/javascript">
            console.log("Starting javascript...")
            function submitSearch() {
                console.log("  Starting submitSearch()...")
                $.ajax({
                    url: "/search",
                    method: "POST",
                    data: $("#search.form").serialize(),
                    success: function(rawData) {
                        var parsed = JSON.parse(rawData);
                        console.log(parsed)
                        console.log("Hello")
                        if (!parsed) return;

                        var searchResults = $("#search.results");
                        searchResults.empty();

                        parsed.forEach(function(result) {
                            var row = $("<tr><td>" + result.Title + "</td><td>" + result.Author + "</td><td>" + result.Year + "</td><td>" + result.ID + "</td></tr>");
                            console.log(row)
                            searchResults.append(row);
                            console.log(searchResults)
                        })
                    }
                })
                return false;
            }
        </script>
    </body>
</html>

使用console.log看起来数据正在通过ajax传递给Javascript,但它没有显示。我一直在想我已经写了一个错字但是如果是这样我就找不到了,而且我对在Javascript中使用ajax来解决它并不熟悉。任何帮助或建议将不胜感激。

1 个答案:

答案 0 :(得分:2)

有两个问题。您正在引用:

var searchResults = $("#search.results");

但在html中是:

<tbody id="search-results">

您应该使用#search-results。阅读表格也有同样的情况:

data: $("#search.form").serialize()