搜尋
首頁後端開發Golang無法正確地將表單序列化為 json

无法正确地将表单序列化为 json

php小編香蕉為您介紹一個常見問題:無法正確地將表單序列化為json。在開發中,我們經常需要將表單資料以json格式傳遞給後端處理。然而,有時候我們會遇到一些問題,例如提交的資料無法正確轉換成json格式。這可能是由於表單中包含了特殊字元或格式不正確所導致的。在本文中,我們將探討一些常見的原因和解決方案,幫助您解決這個問題,確保表單資料正確地序列化為json。

問題內容

我正在嘗試在golang 中創建一個web 應用程序,允許您將收據的詳細資訊輸入到不同的表單中,然後這些表單輸入被序列化為json 對象。但是,我在序列化表單時遇到了麻煩,因為每當我嘗試「提交」收據時,都會收到錯誤訊息。

這是 main.go

package main

import (
    "encoding/json"
    "html/template"
    "log"
    "net/http"
    "strconv"

    "github.com/gorilla/mux"
)

type item struct {
    shortdescription string `json:"shortdescription"`
    price            string `json:"price"`
}

type receipt struct {
    retailer     string `json:"retailer"`
    purchasedate string `json:"purchasedate"`
    purchasetime string `json:"purchasetime"`
    items        []item `json:"items"`
    total        string `json:"total"`
    receiptid    int    `json:"receiptid"`
}

var receiptidcounter int

var receipts = make(map[int]receipt)

func main() {
    r := mux.newrouter()

    r.handlefunc("/", homehandler).methods("get")
    r.handlefunc("/submit", submithandler).methods("post")
    r.handlefunc("/receipt/{id}", receipthandler).methods("get")

    http.handle("/", r)

    log.fatal(http.listenandserve(":8080", nil))
}

func homehandler(w http.responsewriter, r *http.request) {
    t, err := template.parsefiles("templates/home.html")
    if err != nil {
        log.println(err)
        http.error(w, "internal server error", http.statusinternalservererror)
        return
    }

    err = t.execute(w, nil)
    if err != nil {
        log.println(err)
        http.error(w, "internal server error", http.statusinternalservererror)
    }
}

func submithandler(w http.responsewriter, r *http.request) {
    decoder := json.newdecoder(r.body)

    var receipt receipt
    err := decoder.decode(&receipt)
    if err != nil {
        log.println(err)
        http.error(w, "bad request", http.statusbadrequest)
        return
    }

    receiptidcounter++
    receipt.receiptid = receiptidcounter
    receipts[receipt.receiptid] = receipt

    jsonresponse, err := json.marshal(map[string]int{"receiptid": receipt.receiptid})
    if err != nil {
        log.println(err)
        http.error(w, "internal server error", http.statusinternalservererror)
        return
    }

    w.header().set("content-type", "application/json")
    w.write(jsonresponse)
}

func receipthandler(w http.responsewriter, r *http.request) {
    vars := mux.vars(r)
    id, err := strconv.atoi(vars["id"])
    if err != nil {
        log.println(err)
        http.error(w, "bad request", http.statusbadrequest)
        return
    }

    receipt, exists := receipts[id]
    if !exists {
        http.notfound(w, r)
        return
    }

    t, err := template.parsefiles("templates/receipt.html")
    if err != nil {
        log.println(err)
        http.error(w, "internal server error", http.statusinternalservererror)
        return
    }

    err = t.execute(w, receipt)
    if err != nil {
        log.println(err)
        http.error(w, "internal server error", http.statusinternalservererror)
    }
}

這是我的 home.html,這是我主頁的 html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>receipt input form</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1 id="receipt-input-form">receipt input form</h1>
    <form id="receipt-form">
        <label>retailer:</label>
        <input type="text" name="retailer" required><br><br>
        
        <label>purchase date:</label>
        <input type="date" name="purchasedate" required><br><br>
        
        <label>purchase time:</label>
        <input type="time" name="purchasetime" required><br><br>
        
        <div id="items">
            <div class="item">
                <label>short description:</label>
                <input type="text" name="shortdescription[]" required>
                
                <label>price:</label>
                <input type="number" name="price[]" step="0.01" min="0" required>
            </div>
        </div>
        <button type="button" id="add-item-btn">add item</button><br><br>
        
        <label>total:</label>
        <input type="number" name="total" step="0.01" min="0" required><br><br>
        
        <button type="submit">submit</button>
    </form>

    <script>
        $(document).ready(function() {
            var itemcount = 1;
            $('#add-item-btn').click(function() {
                itemcount++;
                var newitem = '<div class="item"><label>short description:</label>' +
                    '<input type="text" name="shortdescription[]" required>' +
                    '<label>price:</label>' +
                    '<input type="number" name="price[]" step="0.01" min="0" required>' +
                    '<button type="button" class="remove-item-btn">remove item</button>' +
                    '</div>';
                $('#items').append(newitem);
            });
            
            $(document).on('click', '.remove-item-btn', function() {
                $(this).parent().remove();
                itemcount--;
            });
            
            $('#receipt-form').submit(function(event) {
                event.preventdefault();
                var form = $(this).serializearray();
                var items = [];
                $('.item').each(function() {
                    var item = {};
                    item.shortdescription = $(this).find('input[name="shortdescription[]"]').val();
                    item.price = $(this).find('input[name="price[]"]').val();
                    items.push(item);
                });
                form.push({ name: "items", value: json.stringify(items) });
                $.ajax({
                    type: "post",
                    url: "/submit",
                    data: form,
                    success: function(response) {
                        window.location.href = "/receipt?id=" + response.receiptid;
                    },
                    error: function(xhr, status, error) {
                        console.log(xhr.responsetext);
                    }
                });
            });
        });
    </script>
</body>
</html>

這是我的receipt.html,這是提交收據後的收據頁面的html。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Receipt Details</title>
</head>
<body>
    <h1 id="Receipt-Details">Receipt Details</h1>
    <ul>
        <li>Retailer: {{.Retailer}}</li>
        <li>Purchase Date: {{.PurchaseDate}}</li>
        <li>Purchase Time: {{.PurchaseTime}}</li>
        <li>Items:</li>
        <ul>
            {{range .Items}}
            <li>{{.ShortDescription}} - {{.Price}}</li>
            {{end}}
        </ul>
        <li>Total: {{.Total}}</li>
    </ul>
</body>
</html>

我嘗試了不同的序列化方法,但沒有任何效果。當我填寫收據表格然後點擊提交時,我希望我會進入收據頁面,顯示該收據的獨特詳細資訊。但是我剛剛收到一個錯誤,我最近的一個錯誤是這樣的: in無效字元「r」尋找值的開頭

解決方法

請如下更新您的 home.html。我將提交請求內容類型更改為 application/json 因為伺服器中的 submithandler 正在尋找 json

$('#receipt-form').submit(function(event) {
    event.preventDefault();
    
    var form = $(this).serializeArray();

    var formObject = {};
    $.each(form,
        function(i, v) {
            if (v.name != "price[]" && v.name != "shortDescription[]") {
                formObject[v.name] = v.value;
            }
        });

    var items = [];
    $('.item').each(function() {
        var item = {};
        item.shortDescription = $(this).find('input[name="shortDescription[]"]').val();
        item.price = $(this).find('input[name="price[]"]').val();
        items.push(item);
    });

    formObject["items"] = items;

    $.ajax({
        type: "POST",
        url: "/submit",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(formObject),
        success: function(response) {
            window.location.href = "/receipt?id=" + response.receiptID;
        },
        error: function(xhr, status, error) {
            console.log(xhr.responseText);
        }
    });
});

以上是無法正確地將表單序列化為 json的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
Golang:Go編程語言解釋了Golang:Go編程語言解釋了Apr 10, 2025 am 11:18 AM

Go語言的核心特性包括垃圾回收、靜態鏈接和並發支持。 1.Go語言的並發模型通過goroutine和channel實現高效並發編程。 2.接口和多態性通過實現接口方法,使得不同類型可以統一處理。 3.基本用法展示了函數定義和調用的高效性。 4.高級用法中,切片提供了動態調整大小的強大功能。 5.常見錯誤如競態條件可以通過gotest-race檢測並解決。 6.性能優化通過sync.Pool重用對象,減少垃圾回收壓力。

Golang的目的:建立高效且可擴展的系統Golang的目的:建立高效且可擴展的系統Apr 09, 2025 pm 05:17 PM

Go語言在構建高效且可擴展的系統中表現出色,其優勢包括:1.高性能:編譯成機器碼,運行速度快;2.並發編程:通過goroutines和channels簡化多任務處理;3.簡潔性:語法簡潔,降低學習和維護成本;4.跨平台:支持跨平台編譯,方便部署。

SQL排序中ORDER BY語句結果為何有時看似隨機?SQL排序中ORDER BY語句結果為何有時看似隨機?Apr 02, 2025 pm 05:24 PM

關於SQL查詢結果排序的疑惑學習SQL的過程中,常常會遇到一些令人困惑的問題。最近,筆者在閱讀《MICK-SQL基礎�...

技術棧收斂是否僅僅是技術棧選型的過程?技術棧收斂是否僅僅是技術棧選型的過程?Apr 02, 2025 pm 05:21 PM

技術棧收斂與技術選型的關係在軟件開發中,技術棧的選擇和管理是一個非常關鍵的問題。最近,有讀者提出了...

如何在Go語言中使用反射對比並處理三個結構體的差異?如何在Go語言中使用反射對比並處理三個結構體的差異?Apr 02, 2025 pm 05:15 PM

Go語言中如何對比並處理三個結構體在Go語言編程中,有時需要對比兩個結構體的差異,並將這些差異應用到第�...

在Go語言中如何查看全局安裝的包?在Go語言中如何查看全局安裝的包?Apr 02, 2025 pm 05:12 PM

在Go語言中如何查看全局安裝的包?在使用Go語言開發過程中,經常會使用go...

GoLand中自定義結構體標籤不顯示怎麼辦?GoLand中自定義結構體標籤不顯示怎麼辦?Apr 02, 2025 pm 05:09 PM

GoLand中自定義結構體標籤不顯示怎麼辦?在使用GoLand進行Go語言開發時,很多開發者會遇到自定義結構體標籤在�...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。