Maison > développement back-end > Golang > le corps du texte

Problème d'affichage des options dans le sélecteur sur la page Web : données pour la boucle {{ range }} non transmises dans le modèle Go

WBOY
Libérer: 2024-02-08 21:20:09
avant
336 Les gens l'ont consulté

在网页上的选择器中显示选项时出现问题:循环 {{ range }} 的数据未在 Go 模板中传递

Dans le processus de développement Web, vous rencontrerez parfois des problèmes, comme certaines options d'affichage lors de l'utilisation du sélecteur. L'un des problèmes courants est que les données de boucle ne sont pas transmises dans les modèles Go. Ce problème peut empêcher le sélecteur d’afficher correctement les options. Pour résoudre ce problème, nous devons inspecter et ajuster les données transmises dans les modèles Go. Dans cet article, l'éditeur PHP Shinichi présentera comment résoudre ce problème et fournira quelques conseils et suggestions pratiques. Nous allons jeter un coup d'oeil!

Contenu du problème

Le problème est que sur une page Web qui utilise un sélecteur pour sélectionner un type de produit, les options (valeurs) dans le sélecteur ne sont pas affichées

<!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>
Copier après la connexion

Bien que cette partie du code avec la sortie du tableau fonctionne très bien

{{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}}
Copier après la connexion

Je souhaite obtenir les données elles-mêmes du tableau qui représente cette structure

package product_types

type ProductTypes struct {
    IDType   string `json:"type_id"`
    NameType string `json:"type_name"`
}
Copier après la connexion

Le résultat du code actuel ressemble maintenant à ceci

结果1

J'ai essayé de le changer pour ceci

<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>
Copier après la connexion

Les résultats se sont améliorés, mais au final il y a eu des doublons

result2

Solution de contournement

J'ai trouvé la réponse à mon problème - je n'ai pas ajouté le chemin d'accès à la table ProductTypes dans app.go

} 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)
        }
    }
Copier après la connexion

Le code initial ressemble à ceci :

} 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)
            }
        }
Copier après la connexion

produit.html :

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:stackoverflow.com
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!