Golang中如何使用jQuery操作HTML文本框

Golang中如何使用jQuery操作HTML文本框 如何用 Golang、jQuery 和 MySQL 实现自动完成文本框

源代码:…

3 回复

如何实现自动完成文本框

你可以使用内置的 HTML “datalist” 元素,并使用 MySQL 来填充选项。

Edit fiddle - JSFiddle - Code Playground

JSFiddle - 代码游乐场

在线测试你的 JavaScript、CSS、HTML 或 CoffeeScript。

更多关于Golang中如何使用jQuery操作HTML文本框的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


这不是jQuery,而是作为Web组件构建的原生JavaScript。

PubSub和逻辑

API HTTP处理程序

package handlers

import (
	"encoding/json"
	"fmt"
	t "github.com/kristiannissen/ideal-octo-bassoon/template"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	str "strings"
)

type Hop struct {
	Name                 string
	Substitutes          string
	Betaacidcomposition  string
	Purpose              string
	Country              string

在Golang中无法直接使用jQuery操作HTML文本框,因为Golang是后端语言,而jQuery是前端JavaScript库。以下是完整的实现方案:

1. 后端Golang API(main.go):

package main

import (
    "database/sql"
    "encoding/json"
    "log"
    "net/http"
    "strings"
    
    _ "github.com/go-sql-driver/mysql"
)

type Suggestion struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

func main() {
    http.HandleFunc("/suggestions", suggestionsHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func suggestionsHandler(w http.ResponseWriter, r *http.Request) {
    query := r.URL.Query().Get("q")
    if query == "" {
        json.NewEncoder(w).Encode([]Suggestion{})
        return
    }

    db, err := sql.Open("mysql", "user:password@/database")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer db.Close()

    rows, err := db.Query("SELECT id, name FROM items WHERE name LIKE ? LIMIT 10", query+"%")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer rows.Close()

    var suggestions []Suggestion
    for rows.Next() {
        var s Suggestion
        if err := rows.Scan(&s.ID, &s.Name); err != nil {
            continue
        }
        suggestions = append(suggestions, s)
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(suggestions)
}

2. 前端HTML + jQuery(index.html):

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <input type="text" id="autocomplete" placeholder="输入搜索内容...">
    <div id="suggestions"></div>

    <script>
    $(document).ready(function() {
        $('#autocomplete').on('input', function() {
            var query = $(this).val();
            
            if (query.length < 2) {
                $('#suggestions').empty();
                return;
            }
            
            $.getJSON('/suggestions?q=' + encodeURIComponent(query), function(data) {
                var suggestions = $('#suggestions');
                suggestions.empty();
                
                $.each(data, function(index, item) {
                    suggestions.append(
                        $('<div>').text(item.name)
                            .addClass('suggestion-item')
                            .data('id', item.id)
                            .click(function() {
                                $('#autocomplete').val(item.name);
                                suggestions.empty();
                            })
                    );
                });
            });
        });
    });
    </script>
    
    <style>
    .suggestion-item {
        padding: 8px;
        border: 1px solid #ddd;
        cursor: pointer;
    }
    .suggestion-item:hover {
        background-color: #f0f0f0;
    }
    </style>
</body>
</html>

3. MySQL表结构:

CREATE TABLE items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    INDEX idx_name (name)
);

运行步骤:

  1. 安装MySQL驱动:go get github.com/go-sql-driver/mysql
  2. 启动Golang服务:go run main.go
  3. 在浏览器中打开index.html
  4. 在文本框中输入内容,系统将从MySQL数据库获取匹配的建议

这个实现中,Golang提供RESTful API,jQuery处理前端交互,MySQL存储数据。当用户在文本框中输入时,jQuery会向Golang后端发送请求,后端查询数据库并返回JSON格式的建议列表。

回到顶部