问题是,在使用 Select 器 Select 产品类型的网页上, Select 器中的选项(值)不会显示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Products</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Список продуктов</h1>


<form id="addProductForm">
    <label for="productName">Product Name:</label>
    <input type="text" id="productName" name="productName" required>

    <label for="weight">Weight:</label>
    <input type="number" id="weight" name="weight" required>

    <label for="typeSelect">Product Type:</label>
    <select class="form-control" id="typeSelect" name="TypeID">
        {{ range .Rows}}
        <option value="{{.ProductType.IDType}}">{{ .ProductType.NameType }}</option>
        {{ end }}
    </select>

    <label for="unit">Unit:</label>
    <input type="text" id="unit" name="unit" required>

    <label for="description">Description:</label>
    <input type="text" id="description" name="description" required>

    <label for="pricePickup">Price Pickup:</label>
    <input type="number" id="pricePickup" name="pricePickup" required>

    <label for="priceDelivery">Price Delivery:</label>
    <input type="number" id="priceDelivery" name="priceDelivery" required>


    <button type="button" onclick="addProduct()">Add Product</button>
</form>


<table id="productTable">
    <tr>
        <th>ID продукта</th>
        <th>ID типа</th>
        <th>Название продукта</th>
        <th>Вес</th>
        <th>Единица измерения</th>
        <th>Описание</th>
        <th>Цена самовывоза</th>
        <th>Цена с доставкой</th>
    </tr>
    {{range .Rows}}
    <tr>
        <td>{{.ProductID}}</td>
        <td>{{.ProductType.NameType}}</td>
        <td>{{.ProductName}}</td>
        <td>{{.Weight}}</td>
        <td>{{.Unit}}</td>
        <td>{{.Description}}</td>
        <td>{{.PricePickup}}</td>
        <td>{{.PriceDelivery}}</td>
    </tr>
    {{end}}
</table>

<script>
    function addProduct() {
        // Получение данных из формы
        var form = document.getElementById("addProductForm");
        var formData = new FormData(form);

        // Отправка данных на сервер
        fetch("/add_product", {
            method: "POST",
            body: formData,
        })
            .then(response => response.json())
            .then(data => {
                // Обработка ответа от сервера
                console.log("Product created:", data);

                // Очистка формы или выполнение других действий при необходимости
                form.reset();
            })
            .catch(error => console.error("Error:", error));
    }


</script>

</body>
</html>

尽管这部分代码与表输出完美地结合在一起,

{{range .Rows}}
<tr>
    <td>{{.ProductID}}</td>
    <td>{{.ProductType.NameType}}</td>
    <td>{{.ProductName}}</td>
    <td>{{.Weight}}</td>
    <td>{{.Unit}}</td>
    <td>{{.Description}}</td>
    <td>{{.PricePickup}}</td>
    <td>{{.PriceDelivery}}</td>
</tr>
{{end}}

我想从表示这种 struct 的表中获取数据本身

package product_types

type ProductTypes struct {
    IDType   string `json:"type_id"`
    NameType string `json:"type_name"`
}

当前代码的结果现在如下所示

result1

我试着把它改成这个

<label for="typeSelect">Product Type:</label>
<select class="form-control" id="typeSelect" name="TypeID">
    {{ range .Rows}}
    <option value="{{.ProductType.IDType}}">{{ .ProductType.NameType }}</option>
    {{ end }}
</select>

结果变得更好了,但最后还是出现了重复的情况

result2

推荐答案

我找到了问题的答案--我没有将路径添加到app.go中的ProductTypes表

} else if req.URL.Path == "/products.html" {
        log.Printf("Обслуживание HTML-файла: %s\n", productsHTMLPath)

        dataRows, err := repoProduct.FindAllProduct(context.TODO()) // Используйте функцию для получения продуктов
        if err != nil {
            http.Error(res, fmt.Sprintf("Запрос не выполнен: %v", err), http.StatusInternalServerError)
            return
        }

        dataRows1, err := repo.FindAll(context.TODO()) // Используйте функцию для получения типов продуктов
        if err != nil {
            http.Error(res, fmt.Sprintf("Запрос не выполнен: %v", err), http.StatusInternalServerError)
            return
        }

        tmpl, err := template.ParseFiles(productsHTMLPath)
        if err != nil {
            http.Error(res, fmt.Sprintf("Не удалось парсирование шаблона: %v", err), http.StatusInternalServerError)
            return
        }

        Rows := struct {
            Products     []products2.Product
            ProductTypes []product_types2.ProductTypes
        }{
            Products:     dataRows,
            ProductTypes: dataRows1,
        }

        err = tmpl.Execute(res, Rows)
        if err != nil {
            http.Error(res, fmt.Sprintf("Не удалось выполнить шаблон: %v", err), http.StatusInternalServerError)
        }
    }

最初,代码如下所示:

} else if req.URL.Path == "/products.html" {
            log.Printf("Обуслуживание HTML-файла: %s\n", productsHTMLPath)

            dataRows, err := repoProduct.FindAllProduct(context.TODO()) // Используйте функцию для получения продуктов
            if err != nil {
                http.Error(res, fmt.Sprintf("Запрос не выполнен: %v", err), http.StatusInternalServerError)
                return
            }

            tmpl, err := template.ParseFiles(productsHTMLPath)
            if err != nil {
                http.Error(res, fmt.Sprintf("Не удалось парсирование шаблона: %v", err), http.StatusInternalServerError)
                return
            }

            err = tmpl.Execute(res, struct{ Rows []products2.Product }{dataRows})
            if err != nil {
                http.Error(res, fmt.Sprintf("Не удалось выполнить шаблон: %v", err), http.StatusInternalServerError)
            }
        }

Product.html:

<label for="typeSelect">Product Type:</label>
    <select class="form-control" id="typeSelect" name="TypeID">
        {{ range .ProductTypes}}
        <option value="{{.IDType}}">{{ .NameType }}</option>
        {{ end }}
</select>

Html相关问答推荐

如何获得一个背景图像,不是模糊的内部容器,但模糊的外部'

输入宽度在表格显示上不起作用FLEX溢出隐藏Firefox

悬停效果在新西兰表上不起作用

需要帮助创建一个简单的html css网格布局

如何用等宽字体固定数字在有序列表中的位置

浏览器是否可以呈现存储在代码点0x09处的字形?

如何在ASP.NET Core中添加换行符

为什么一个 CSS 网格框比其他网格框低?

如果使用复选框属性更改,如何防止事件更改?

我如何使用 html 在表格的单元格内实现下面显示的背景 colored颜色 加载器(请判断设计参考的图像链接)

如何在 flex 项目中忽略子元素的宽度

css 网格创建空行和列

高度大于页面高度和页面大于覆盖的 CSS 覆盖

使用 R 中的 rvest 包获取搜索结果的第一个链接

增加第一个字母的大小不再正确居中文本

如何在没有容器的情况下沿基线将 div 中的元素居中?

在 html 邮箱的左侧和右侧制作多个元素很热门吗?

圆形边框显示在该部分后面.怎么修?

AWS SES:如何正确使用 CSS

无法使用 Reactjs 多次更新本地存储