
在网页开发过程中,有时会遇到一些问题,比如在使用选择器时出现了一些显示选项的问题。其中一个常见问题是循环数据未在Go模板中传递。这个问题可能会导致选择器无法正确显示选项。为了解决这个问题,我们需要对Go模板中的数据传递进行检查和调整。在本文中,php小编新一将向大家介绍如何解决这个问题,并提供一些实用的技巧和建议。让我们一起来看看吧!
问题在于,在使用选择器选择产品类型的网页上,选择器内的选项(值)不会显示
<!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}}我想从代表这种结构的表中获取数据本身
package product_types
type ProductTypes struct {
IDType string `json:"type_id"`
NameType string `json:"type_name"`
}当前代码的结果现在看起来像这样
结果1
我尝试将其更改为这样
<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)
}
}产品.html:
<label for="typeSelect">Product Type:</label>
<select class="form-control" id="typeSelect" name="TypeID">
{{ range .ProductTypes}}
<option value="{{.IDType}}">{{ .NameType }}</option>
{{ end }}
</select>以上就是在网页上的选择器中显示选项时出现问题:循环 {{ range }} 的数据未在 Go 模板中传递的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号