Golang程序如何与客户端协同工作

Golang程序如何与客户端协同工作 我正在为一个Golang电子商务网站积累经验。为了展示记录,我使用了模板。运行我的四个函数并在客户端存储数组的最佳/最简单方法是什么?这些函数用于更改和隐藏记录,目前是用JavaScript编写的。该数组用于跟踪在多次搜索中购买了多少产品。请问我能得到一些帮助吗?如果您能想到任何改进这个请求的方法,请告诉我,好吗?谢谢!

我尝试过查找模板和Golang的资料。我见过各种用于Golang和JavaScript的库,并注意到它们存在问题。我找到了gopherjs。我考虑过可能的帮助和文档。我尝试过视频,但印象不深。

这是我的源代码,这三个函数尚未经过测试。程序通过模板按钮运行。

playground

编辑:哦,程序列出了数据库中包含关键字的记录。


更多关于Golang程序如何与客户端协同工作的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

你可以尝试使用 gorilla sessions

更多关于Golang程序如何与客户端协同工作的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


感谢关于本地存储的提示,如果有人看到这个,我的问题已经解决了。我只是重新清理以重置图形用户界面的值。

要删除一条记录,可以这样做:

.test100 {
    visibility: hidden;
}

并在重新清理时,使用类似 {{.a_value}} 这样的方式将 div 的值设置为 test100。

.

JoshuaE: 在客户端运行我的四个函数并存储数组,最佳/最简单的方法是什么?

我在某些情况下使用过 localStorage。你也可以用它来存储数组。

Edit fiddle - JSFiddle - Code Playground

Edit fiddle - JSFiddle - Code Playground

在线使用 JSFiddle 代码编辑器测试你的 JavaScript、CSS、HTML 或 CoffeeScript。

在Go中与客户端协同工作,可以通过模板渲染结合JavaScript来实现。以下是针对你需求的解决方案:

1. 通过模板传递数据到JavaScript

在Go模板中嵌入数据,让JavaScript可以直接使用:

// main.go
package main

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

type Product struct {
    ID    int
    Name  string
    Price float64
}

func main() {
    tmpl := template.Must(template.ParseFiles("index.html"))
    
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // 模拟从数据库获取产品数据
        products := []Product{
            {ID: 1, Name: "Laptop", Price: 999.99},
            {ID: 2, Name: "Mouse", Price: 29.99},
            {ID: 3, Name: "Keyboard", Price: 89.99},
        }
        
        // 将数据传递给模板
        data := map[string]interface{}{
            "Products": products,
        }
        
        tmpl.Execute(w, data)
    })
    
    http.ListenAndServe(":8080", nil)
}

2. 在模板中嵌入JavaScript数组

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>E-commerce Site</title>
</head>
<body>
    <h1>Products</h1>
    <div id="products">
        {{range .Products}}
        <div class="product" data-id="{{.ID}}">
            <h3>{{.Name}}</h3>
            <p>Price: ${{.Price}}</p>
            <button onclick="addToCart({{.ID}}, '{{.Name}}', {{.Price}})">Add to Cart</button>
        </div>
        {{end}}
    </div>
    
    <div id="cart">
        <h2>Shopping Cart</h2>
        <div id="cart-items"></div>
        <button onclick="hideCart()">Hide Cart</button>
        <button onclick="showCart()">Show Cart</button>
    </div>
    
    <script>
        // 从Go模板接收数据
        let productsData = [
            {{range .Products}}
            {id: {{.ID}}, name: "{{.Name}}", price: {{.Price}}},
            {{end}}
        ];
        
        // 购物车数组 - 存储购买记录
        let shoppingCart = [];
        let purchaseHistory = [];
        
        // 添加产品到购物车
        function addToCart(id, name, price) {
            const product = {id, name, price, quantity: 1};
            const existingIndex = shoppingCart.findIndex(item => item.id === id);
            
            if (existingIndex > -1) {
                shoppingCart[existingIndex].quantity++;
            } else {
                shoppingCart.push(product);
            }
            
            updateCartDisplay();
            saveCartToStorage();
        }
        
        // 更新购物车显示
        function updateCartDisplay() {
            const cartItems = document.getElementById('cart-items');
            cartItems.innerHTML = '';
            
            shoppingCart.forEach(item => {
                const itemDiv = document.createElement('div');
                itemDiv.className = 'cart-item';
                itemDiv.innerHTML = `
                    ${item.name} - $${item.price} x ${item.quantity}
                    <button onclick="removeFromCart(${item.id})">Remove</button>
                `;
                cartItems.appendChild(itemDiv);
            });
        }
        
        // 从购物车移除产品
        function removeFromCart(id) {
            shoppingCart = shoppingCart.filter(item => item.id !== id);
            updateCartDisplay();
            saveCartToStorage();
        }
        
        // 隐藏购物车
        function hideCart() {
            document.getElementById('cart').style.display = 'none';
        }
        
        // 显示购物车
        function showCart() {
            document.getElementById('cart').style.display = 'block';
        }
        
        // 保存购物车到本地存储
        function saveCartToStorage() {
            localStorage.setItem('shoppingCart', JSON.stringify(shoppingCart));
        }
        
        // 从本地存储加载购物车
        function loadCartFromStorage() {
            const savedCart = localStorage.getItem('shoppingCart');
            if (savedCart) {
                shoppingCart = JSON.parse(savedCart);
                updateCartDisplay();
            }
        }
        
        // 记录购买历史
        function recordPurchase() {
            if (shoppingCart.length > 0) {
                purchaseHistory.push({
                    timestamp: new Date().toISOString(),
                    items: [...shoppingCart],
                    total: shoppingCart.reduce((sum, item) => sum + (item.price * item.quantity), 0)
                });
                
                // 保存到本地存储
                localStorage.setItem('purchaseHistory', JSON.stringify(purchaseHistory));
                
                // 清空购物车
                shoppingCart = [];
                updateCartDisplay();
                saveCartToStorage();
            }
        }
        
        // 页面加载时初始化
        window.onload = function() {
            loadCartFromStorage();
            
            // 加载购买历史
            const savedHistory = localStorage.getItem('purchaseHistory');
            if (savedHistory) {
                purchaseHistory = JSON.parse(savedHistory);
            }
        };
    </script>
</body>
</html>

3. 通过AJAX与Go后端通信

如果需要将数据传回Go服务器:

// 添加API端点处理购物车数据
http.HandleFunc("/api/cart", func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    
    if r.Method == "POST" {
        // 处理购物车提交
        var cartData []struct {
            ID       int     `json:"id"`
            Quantity int     `json:"quantity"`
        }
        
        json.NewDecoder(r.Body).Decode(&cartData)
        
        // 处理购物车逻辑...
        json.NewEncoder(w).Encode(map[string]string{"status": "success"})
    }
})

4. 使用JSON API提供数据

// 提供JSON格式的产品数据
http.HandleFunc("/api/products", func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    
    products := []Product{
        {ID: 1, Name: "Laptop", Price: 999.99},
        {ID: 2, Name: "Mouse", Price: 29.99},
    }
    
    json.NewEncoder(w).Encode(products)
})

这个方案使用Go模板渲染初始页面,JavaScript处理客户端交互,localStorage持久化购物车数据。购物车数组shoppingCart跟踪当前会话的产品,purchaseHistory记录多次搜索中的购买历史。

回到顶部